blob: 0c06c8bb9c7b8eba435b23658475b71a48d1c2fc [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;
61
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070062namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070063const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070064const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080065#if USE_MTD
66const int kUbiVolumeAttachTimeout = 5 * 60;
67#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080068
69FileDescriptorPtr CreateFileDescriptor(const char* path) {
70 FileDescriptorPtr ret;
71#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080072 if (strstr(path, "/dev/ubi") == path) {
73 if (!UbiFileDescriptor::IsUbi(path)) {
74 // The volume might not have been attached at boot time.
75 int volume_no;
76 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
77 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
78 }
79 }
80 if (UbiFileDescriptor::IsUbi(path)) {
81 LOG(INFO) << path << " is a UBI device.";
82 ret.reset(new UbiFileDescriptor);
83 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080084 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080085 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080086 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080087 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080088 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080089#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080090 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080091#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070092 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080093#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080094 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070095}
96
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080097// Opens path for read/write. On success returns an open FileDescriptor
98// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
99FileDescriptorPtr OpenFile(const char* path, int* err) {
100 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800101 int mode = O_RDWR;
102#if USE_MTD
103 // On NAND devices, we can either read, or write, but not both. So here we
104 // use O_WRONLY.
105 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
106 mode = O_WRONLY;
107 }
108#endif
109 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800110 *err = errno;
111 PLOG(ERROR) << "Unable to open file " << path;
112 return nullptr;
113 }
114 *err = 0;
115 return fd;
116}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700117} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700118
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800119
120// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
121// arithmetic.
122static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
123 return part * norm / total;
124}
125
126void DeltaPerformer::LogProgress(const char* message_prefix) {
127 // Format operations total count and percentage.
128 string total_operations_str("?");
129 string completed_percentage_str("");
130 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700131 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800132 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
133 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700134 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700135 IntRatio(next_operation_num_, num_total_operations_,
136 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800137 }
138
139 // Format download total count and percentage.
140 size_t payload_size = install_plan_->payload_size;
141 string payload_size_str("?");
142 string downloaded_percentage_str("");
143 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700144 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800145 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
146 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700147 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700148 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800149 }
150
151 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
152 << "/" << total_operations_str << " operations"
153 << completed_percentage_str << ", " << total_bytes_received_
154 << "/" << payload_size_str << " bytes downloaded"
155 << downloaded_percentage_str << ", overall progress "
156 << overall_progress_ << "%";
157}
158
159void DeltaPerformer::UpdateOverallProgress(bool force_log,
160 const char* message_prefix) {
161 // Compute our download and overall progress.
162 unsigned new_overall_progress = 0;
163 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
164 progress_weight_dont_add_up);
165 // Only consider download progress if its total size is known; otherwise
166 // adjust the operations weight to compensate for the absence of download
167 // progress. Also, make sure to cap the download portion at
168 // kProgressDownloadWeight, in case we end up downloading more than we
169 // initially expected (this indicates a problem, but could generally happen).
170 // TODO(garnold) the correction of operations weight when we do not have the
171 // total payload size, as well as the conditional guard below, should both be
172 // eliminated once we ensure that the payload_size in the install plan is
173 // always given and is non-zero. This currently isn't the case during unit
174 // tests (see chromium-os:37969).
175 size_t payload_size = install_plan_->payload_size;
176 unsigned actual_operations_weight = kProgressOperationsWeight;
177 if (payload_size)
178 new_overall_progress += min(
179 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
180 kProgressDownloadWeight)),
181 kProgressDownloadWeight);
182 else
183 actual_operations_weight += kProgressDownloadWeight;
184
185 // Only add completed operations if their total number is known; we definitely
186 // expect an update to have at least one operation, so the expectation is that
187 // this will eventually reach |actual_operations_weight|.
188 if (num_total_operations_)
189 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
190 actual_operations_weight);
191
192 // Progress ratio cannot recede, unless our assumptions about the total
193 // payload size, total number of operations, or the monotonicity of progress
194 // is breached.
195 if (new_overall_progress < overall_progress_) {
196 LOG(WARNING) << "progress counter receded from " << overall_progress_
197 << "% down to " << new_overall_progress << "%; this is a bug";
198 force_log = true;
199 }
200 overall_progress_ = new_overall_progress;
201
202 // Update chunk index, log as needed: if forced by called, or we completed a
203 // progress chunk, or a timeout has expired.
204 base::Time curr_time = base::Time::Now();
205 unsigned curr_progress_chunk =
206 overall_progress_ * kProgressLogMaxChunks / 100;
207 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
208 curr_time > forced_progress_log_time_) {
209 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
210 LogProgress(message_prefix);
211 }
212 last_progress_chunk_ = curr_progress_chunk;
213}
214
215
Gilad Arnoldfe133932014-01-14 12:25:50 -0800216size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
217 size_t max) {
218 const size_t count = *count_p;
219 if (!count)
220 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700221 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800222 const char* bytes_start = *bytes_p;
223 const char* bytes_end = bytes_start + read_len;
224 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
225 *bytes_p = bytes_end;
226 *count_p = count - read_len;
227 return read_len;
228}
229
230
231bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
232 ErrorCode* error) {
233 if (op_result)
234 return true;
235
236 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
237 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700238 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800239 return false;
240}
241
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700242int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700243 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800244 fd_ = OpenFile(path, &err);
245 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700246 path_ = path;
247 return -err;
248}
249
250bool DeltaPerformer::OpenKernel(const char* kernel_path) {
251 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800252 kernel_fd_ = OpenFile(kernel_path, &err);
253 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700254 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800255 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700256}
257
Alex Deymo1beda782015-06-07 23:01:25 +0200258bool DeltaPerformer::OpenSourceRootfs(const string& source_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800259 int err;
260 source_fd_ = OpenFile(source_path.c_str(), &err);
261 return static_cast<bool>(source_fd_);
262}
263
Alex Deymo1beda782015-06-07 23:01:25 +0200264bool DeltaPerformer::OpenSourceKernel(const string& source_kernel_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800265 int err;
266 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
267 return static_cast<bool>(source_kernel_fd_);
268}
269
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700270int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700271 int err = 0;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800272 if (!kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700273 err = errno;
274 PLOG(ERROR) << "Unable to close kernel fd:";
275 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800276 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700277 err = errno;
278 PLOG(ERROR) << "Unable to close rootfs fd:";
279 }
Allie Woodfdf00512015-03-02 13:34:55 -0800280 if (source_fd_ && !source_fd_->Close()) {
281 err = errno;
282 PLOG(ERROR) << "Unable to close source rootfs fd:";
283 }
284 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
285 err = errno;
286 PLOG(ERROR) << "Unable to close source kernel fd:";
287 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700288 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800289 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800290 kernel_fd_.reset();
291 source_fd_.reset();
292 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700293 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800294 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700295 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
296 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800297 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800298 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700299 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700300}
301
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700302namespace {
303
304void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800305 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800306 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
307 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700308}
309
310void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
311 if (manifest.has_old_kernel_info())
312 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
313 if (manifest.has_old_rootfs_info())
314 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
315 if (manifest.has_new_kernel_info())
316 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
317 if (manifest.has_new_rootfs_info())
318 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
319}
320
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700321} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700322
Don Garrett4d039442013-10-28 18:40:06 -0700323uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800324 // Manifest size is stored right after the magic string and the version.
325 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700326}
327
Jay Srinivasanf4318702012-09-24 11:56:24 -0700328uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800329 // Manifest size is stored right after the magic string and the version.
330 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700331}
332
333uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800334 // Actual manifest begins right after the manifest size field.
335 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700336}
337
Gilad Arnoldfe133932014-01-14 12:25:50 -0800338uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800339 return metadata_size_;
340}
341
Allie Woodfdf00512015-03-02 13:34:55 -0800342uint32_t DeltaPerformer::GetMinorVersion() const {
343 if (manifest_.has_minor_version()) {
344 return manifest_.minor_version();
345 } else {
346 return (install_plan_->is_full_update ?
347 kFullPayloadMinorVersion :
348 kSupportedMinorPayloadVersion);
349 }
350}
351
Gilad Arnolddaa27402014-01-23 11:56:17 -0800352bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
353 if (!manifest_parsed_)
354 return false;
355 *out_manifest_p = manifest_;
356 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800357}
358
Jay Srinivasanf4318702012-09-24 11:56:24 -0700359
Darin Petkov9574f7e2011-01-13 10:48:12 -0800360DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800361 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700362 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700363 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800364 uint64_t manifest_size = (metadata_size_ ?
365 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700366
Gilad Arnoldfe133932014-01-14 12:25:50 -0800367 if (!manifest_size) {
368 // Ensure we have data to cover the payload header.
369 if (payload.size() < manifest_offset)
370 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700371
Gilad Arnoldfe133932014-01-14 12:25:50 -0800372 // Validate the magic string.
373 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
374 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700375 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800376 return kMetadataParseError;
377 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800378
379 // Extract the payload version from the metadata.
380 uint64_t major_payload_version;
381 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
382 major_payload_version_size_mismatch);
383 memcpy(&major_payload_version,
384 &payload[GetVersionOffset()],
385 kDeltaVersionSize);
386 // switch big endian to host
387 major_payload_version = be64toh(major_payload_version);
388
389 if (major_payload_version != kSupportedMajorPayloadVersion) {
390 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
391 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700392 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800393 return kMetadataParseError;
394 }
395
396 // Next, parse the manifest size.
397 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
398 manifest_size_size_mismatch);
399 memcpy(&manifest_size,
400 &payload[GetManifestSizeOffset()],
401 kDeltaManifestSizeSize);
402 manifest_size = be64toh(manifest_size); // switch big endian to host
403
404 // If the metadata size is present in install plan, check for it immediately
405 // even before waiting for that many number of bytes to be downloaded in the
406 // payload. This will prevent any attack which relies on us downloading data
407 // beyond the expected metadata size.
408 metadata_size_ = manifest_offset + manifest_size;
409 if (install_plan_->hash_checks_mandatory) {
410 if (install_plan_->metadata_size != metadata_size_) {
411 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
412 << install_plan_->metadata_size
413 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700414 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800415 return kMetadataParseError;
416 }
417 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700418 }
419
420 // Now that we have validated the metadata size, we should wait for the full
421 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800422 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800423 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700424
425 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700426 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700427 // that we just log once (instead of logging n times) if it takes n
428 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800429 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700430 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800431 } else {
432 // For mandatory-cases, we'd have already returned a kMetadataParseError
433 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
434 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
435 << install_plan_->metadata_size
436 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800437 << "Trusting metadata size in payload = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700438 SendUmaStat(ErrorCode::kDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800439 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700440
Jay Srinivasanf4318702012-09-24 11:56:24 -0700441 // We have the full metadata in |payload|. Verify its integrity
442 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800443 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700444 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800445 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800446 // The autoupdate_CatchBadSignatures test checks for this string
447 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800448 LOG(ERROR) << "Mandatory metadata signature validation failed";
449 return kMetadataParseError;
450 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700451
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800452 // For non-mandatory cases, just send a UMA stat.
453 LOG(WARNING) << "Ignoring metadata signature validation failures";
454 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700455 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700456 }
457
Gilad Arnolddaa27402014-01-23 11:56:17 -0800458 // The payload metadata is deemed valid, it's safe to parse the protobuf.
459 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800460 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700461 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800462 return kMetadataParseError;
463 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800464
465 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800466 return kMetadataParseSuccess;
467}
468
Don Garrette410e0f2011-11-10 15:39:01 -0800469// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800470// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700471// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800472bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700473 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700474
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700475 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800476 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800477
478 // Update the total byte downloaded count and the progress logs.
479 total_bytes_received_ += count;
480 UpdateOverallProgress(false, "Completed ");
481
Gilad Arnoldfe133932014-01-14 12:25:50 -0800482 while (!manifest_valid_) {
483 // Read data up to the needed limit; this is either the payload header size,
484 // or the full metadata size (once it becomes known).
485 const bool do_read_header = !metadata_size_;
486 CopyDataToBuffer(&c_bytes, &count,
487 (do_read_header ? GetManifestOffset() :
488 metadata_size_));
489
Gilad Arnolddaa27402014-01-23 11:56:17 -0800490 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700491 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800492 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800493 if (result == kMetadataParseInsufficientData) {
494 // If we just processed the header, make an attempt on the manifest.
495 if (do_read_header && metadata_size_)
496 continue;
497
Don Garrette410e0f2011-11-10 15:39:01 -0800498 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800499 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700500
501 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700502 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700503 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800504 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700505
Gilad Arnoldfe133932014-01-14 12:25:50 -0800506 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800507 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700508 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800509 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700510 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700511
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700512 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700513 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700514 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700515 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800516 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700517 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800518
Allie Woodfdf00512015-03-02 13:34:55 -0800519 // Open source fds if we have a delta payload with minor version 2.
520 if (!install_plan_->is_full_update &&
521 GetMinorVersion() == kSourceMinorPayloadVersion) {
522 if (!OpenSourceRootfs(install_plan_->source_path)) {
523 LOG(ERROR) << "Unable to open source rootfs partition file "
524 << install_plan_->source_path;
525 Close();
526 return false;
527 }
528 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
529 LOG(ERROR) << "Unable to open source kernel partition file "
530 << install_plan_->kernel_source_path;
531 Close();
532 return false;
533 }
534 }
535
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800536 num_rootfs_operations_ = manifest_.install_operations_size();
537 num_total_operations_ =
538 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
539 if (next_operation_num_ > 0)
540 UpdateOverallProgress(true, "Resuming after ");
541 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700542 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800543
544 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700545 // Check if we should cancel the current attempt for any reason.
546 // In this case, *error will have already been populated with the reason
547 // why we're cancelling.
548 if (system_state_->update_attempter()->ShouldCancel(error))
549 return false;
550
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800551 const bool is_kernel_partition =
552 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700553 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800554 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700555 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800556 next_operation_num_ - num_rootfs_operations_) :
557 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800558
559 CopyDataToBuffer(&c_bytes, &count, op.data_length());
560
561 // Check whether we received all of the next operation's data payload.
562 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700563 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700564
Jay Srinivasanf4318702012-09-24 11:56:24 -0700565 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700566 // Otherwise, keep the old behavior. This serves as a knob to disable
567 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800568 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
569 // we would have already failed in ParsePayloadMetadata method and thus not
570 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700571 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700572 // Note: Validate must be called only if CanPerformInstallOperation is
573 // called. Otherwise, we might be failing operations before even if there
574 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800575 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700576 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800577 if (install_plan_->hash_checks_mandatory) {
578 LOG(ERROR) << "Mandatory operation hash check failed";
579 return false;
580 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700581
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800582 // For non-mandatory cases, just send a UMA stat.
583 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700584 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700585 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700586 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700587 }
588
Darin Petkov45580e42010-10-08 14:02:40 -0700589 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700590 ScopedTerminatorExitUnblocker exit_unblocker =
591 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800592
593 bool op_result;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700594 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
Gilad Arnoldfe133932014-01-14 12:25:50 -0800595 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ)
596 op_result = HandleOpResult(
597 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
598 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
599 op_result = HandleOpResult(
600 PerformMoveOperation(op, is_kernel_partition), "move", error);
601 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF)
602 op_result = HandleOpResult(
603 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
Allie Wood9f6f0a52015-03-30 11:25:47 -0700604 else if (op.type() ==
605 DeltaArchiveManifest_InstallOperation_Type_SOURCE_COPY)
606 op_result =
607 HandleOpResult(PerformSourceCopyOperation(op, is_kernel_partition),
608 "source_copy", error);
609 else if (op.type() ==
610 DeltaArchiveManifest_InstallOperation_Type_SOURCE_BSDIFF)
611 op_result =
612 HandleOpResult(PerformSourceBsdiffOperation(op, is_kernel_partition),
613 "source_bsdiff", error);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800614 else
615 op_result = HandleOpResult(false, "unknown", error);
616
617 if (!op_result)
618 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800619
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700620 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800621 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700622 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700623 }
Don Garrette410e0f2011-11-10 15:39:01 -0800624 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700625}
626
David Zeuthen8f191b22013-08-06 12:27:50 -0700627bool DeltaPerformer::IsManifestValid() {
628 return manifest_valid_;
629}
630
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700631bool DeltaPerformer::CanPerformInstallOperation(
632 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
633 operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700634 // Move and source_copy operations don't require any data blob, so they can
635 // always be performed.
636 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
637 operation.type() ==
638 DeltaArchiveManifest_InstallOperation_Type_SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700639 return true;
640
641 // See if we have the entire data blob in the buffer
642 if (operation.data_offset() < buffer_offset_) {
643 LOG(ERROR) << "we threw away data it seems?";
644 return false;
645 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700646
Gilad Arnoldfe133932014-01-14 12:25:50 -0800647 return (operation.data_offset() + operation.data_length() <=
648 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700649}
650
651bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700652 const DeltaArchiveManifest_InstallOperation& operation,
653 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654 CHECK(operation.type() == \
655 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
656 operation.type() == \
657 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
658
659 // Since we delete data off the beginning of the buffer as we use it,
660 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700661 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
662 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700663
Darin Petkov437adc42010-10-07 13:12:24 -0700664 // Extract the signature message if it's in this operation.
665 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700666
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700667 DirectExtentWriter direct_writer;
668 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700669 unique_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700670
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700671 // Since bzip decompression is optional, we have a variable writer that will
672 // point to one of the ExtentWriter objects above.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700673 ExtentWriter* writer = nullptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700674 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
675 writer = &zero_pad_writer;
676 } else if (operation.type() ==
677 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
678 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
679 writer = bzip_writer.get();
680 } else {
681 NOTREACHED();
682 }
683
684 // Create a vector of extents to pass to the ExtentWriter.
685 vector<Extent> extents;
686 for (int i = 0; i < operation.dst_extents_size(); i++) {
687 extents.push_back(operation.dst_extents(i));
688 }
689
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800690 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700691
692 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800693 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700694 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700695
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700696 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800697 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700698 return true;
699}
700
701bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700702 const DeltaArchiveManifest_InstallOperation& operation,
703 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700704 // Calculate buffer size. Note, this function doesn't do a sliding
705 // window to copy in case the source and destination blocks overlap.
706 // If we wanted to do a sliding window, we could program the server
707 // to generate deltas that effectively did a sliding window.
708
709 uint64_t blocks_to_read = 0;
710 for (int i = 0; i < operation.src_extents_size(); i++)
711 blocks_to_read += operation.src_extents(i).num_blocks();
712
713 uint64_t blocks_to_write = 0;
714 for (int i = 0; i < operation.dst_extents_size(); i++)
715 blocks_to_write += operation.dst_extents(i).num_blocks();
716
717 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800718 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700719
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800720 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700721
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700722 // Read in bytes.
723 ssize_t bytes_read = 0;
724 for (int i = 0; i < operation.src_extents_size(); i++) {
725 ssize_t bytes_read_this_iteration = 0;
726 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200727 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700728 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
729 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
730 &buf[bytes_read],
731 bytes,
732 extent.start_block() * block_size_,
733 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700734 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200735 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700736 bytes_read += bytes_read_this_iteration;
737 }
738
739 // Write bytes out.
740 ssize_t bytes_written = 0;
741 for (int i = 0; i < operation.dst_extents_size(); i++) {
742 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200743 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700744 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
745 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
746 &buf[bytes_written],
747 bytes,
748 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200749 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700750 }
751 DCHECK_EQ(bytes_written, bytes_read);
752 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
753 return true;
754}
755
Allie Wood9f6f0a52015-03-30 11:25:47 -0700756namespace {
757
758// Takes |extents| and fills an empty vector |blocks| with a block index for
759// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
760void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
761 vector<uint64_t>* blocks) {
762 for (Extent ext : extents) {
763 for (uint64_t j = 0; j < ext.num_blocks(); j++)
764 blocks->push_back(ext.start_block() + j);
765 }
766}
767
768// Takes |extents| and returns the number of blocks in those extents.
769uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
770 uint64_t sum = 0;
771 for (Extent ext : extents) {
772 sum += ext.num_blocks();
773 }
774 return sum;
775}
776
777} // namespace
778
779bool DeltaPerformer::PerformSourceCopyOperation(
780 const DeltaArchiveManifest_InstallOperation& operation,
781 bool is_kernel_partition) {
782 if (operation.has_src_length())
783 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
784 if (operation.has_dst_length())
785 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
786
787 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
788 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
789 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
790
791 // Create vectors of all the individual src/dst blocks.
792 vector<uint64_t> src_blocks;
793 vector<uint64_t> dst_blocks;
794 ExtentsToBlocks(operation.src_extents(), &src_blocks);
795 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
796 DCHECK_EQ(src_blocks.size(), blocks_to_read);
797 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
798
799 FileDescriptorPtr src_fd =
800 is_kernel_partition ? source_kernel_fd_ : source_fd_;
801 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
802
803 chromeos::Blob buf(block_size_);
804 ssize_t bytes_read = 0;
805 // Read/write one block at a time.
806 for (uint64_t i = 0; i < blocks_to_read; i++) {
807 ssize_t bytes_read_this_iteration = 0;
808 uint64_t src_block = src_blocks[i];
809 uint64_t dst_block = dst_blocks[i];
810
811 // Read in bytes.
812 TEST_AND_RETURN_FALSE(
813 utils::PReadAll(src_fd,
814 buf.data(),
815 block_size_,
816 src_block * block_size_,
817 &bytes_read_this_iteration));
818
819 // Write bytes out.
820 TEST_AND_RETURN_FALSE(
821 utils::PWriteAll(dst_fd,
822 buf.data(),
823 block_size_,
824 dst_block * block_size_));
825
826 bytes_read += bytes_read_this_iteration;
827 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
828 static_cast<ssize_t>(block_size_));
829 }
830 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
831 return true;
832}
833
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700834bool DeltaPerformer::ExtentsToBsdiffPositionsString(
835 const RepeatedPtrField<Extent>& extents,
836 uint64_t block_size,
837 uint64_t full_length,
838 string* positions_string) {
839 string ret;
840 uint64_t length = 0;
841 for (int i = 0; i < extents.size(); i++) {
842 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700843 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700844 uint64_t this_length = min(full_length - length,
845 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700846 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700847 length += this_length;
848 }
849 TEST_AND_RETURN_FALSE(length == full_length);
850 if (!ret.empty())
851 ret.resize(ret.size() - 1); // Strip trailing comma off
852 *positions_string = ret;
853 return true;
854}
855
856bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700857 const DeltaArchiveManifest_InstallOperation& operation,
858 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700859 // Since we delete data off the beginning of the buffer as we use it,
860 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700861 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
862 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700863
864 string input_positions;
865 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
866 block_size_,
867 operation.src_length(),
868 &input_positions));
869 string output_positions;
870 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
871 block_size_,
872 operation.dst_length(),
873 &output_positions));
874
875 string temp_filename;
876 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
877 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700878 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700879 ScopedPathUnlinker path_unlinker(temp_filename);
880 {
881 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
882 ScopedFdCloser fd_closer(&fd);
883 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800884 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700885 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700886
Darin Petkov7f2ec752013-04-03 14:45:19 +0200887 // Update the buffer to release the patch data memory as soon as the patch
888 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800889 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200890
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800891 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700892 vector<string> cmd{kBspatchPath, path, path, temp_filename,
893 input_positions, output_positions};
894
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700895 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700896 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700897 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
898 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700899 TEST_AND_RETURN_FALSE(return_code == 0);
900
901 if (operation.dst_length() % block_size_) {
902 // Zero out rest of final block.
903 // TODO(adlr): build this into bspatch; it's more efficient that way.
904 const Extent& last_extent =
905 operation.dst_extents(operation.dst_extents_size() - 1);
906 const uint64_t end_byte =
907 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
908 const uint64_t begin_byte =
909 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800910 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800911 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700912 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800913 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700914 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700915 return true;
916}
917
Allie Wood9f6f0a52015-03-30 11:25:47 -0700918bool DeltaPerformer::PerformSourceBsdiffOperation(
919 const DeltaArchiveManifest_InstallOperation& operation,
920 bool is_kernel_partition) {
921 // Since we delete data off the beginning of the buffer as we use it,
922 // the data we need should be exactly at the beginning of the buffer.
923 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
924 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
925 if (operation.has_src_length())
926 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
927 if (operation.has_dst_length())
928 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
929
930 string input_positions;
931 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
932 block_size_,
933 operation.src_length(),
934 &input_positions));
935 string output_positions;
936 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
937 block_size_,
938 operation.dst_length(),
939 &output_positions));
940
941 string temp_filename;
942 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
943 &temp_filename,
944 nullptr));
945 ScopedPathUnlinker path_unlinker(temp_filename);
946 {
947 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
948 ScopedFdCloser fd_closer(&fd);
949 TEST_AND_RETURN_FALSE(
950 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
951 }
952
953 // Update the buffer to release the patch data memory as soon as the patch
954 // file is written out.
955 DiscardBuffer(true);
956
957 const string& src_path = is_kernel_partition ?
958 install_plan_->kernel_source_path :
959 install_plan_->source_path;
960 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
961 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
962 input_positions, output_positions};
963
964 int return_code = 0;
965 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700966 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
967 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -0700968 TEST_AND_RETURN_FALSE(return_code == 0);
969 return true;
970}
971
Darin Petkovd7061ab2010-10-06 14:37:09 -0700972bool DeltaPerformer::ExtractSignatureMessage(
973 const DeltaArchiveManifest_InstallOperation& operation) {
974 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
975 !manifest_.has_signatures_offset() ||
976 manifest_.signatures_offset() != operation.data_offset()) {
977 return false;
978 }
979 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
980 manifest_.signatures_size() == operation.data_length());
981 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
982 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
983 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700984 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700985 buffer_.begin(),
986 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700987
988 // Save the signature blob because if the update is interrupted after the
989 // download phase we don't go through this path anymore. Some alternatives to
990 // consider:
991 //
992 // 1. On resume, re-download the signature blob from the server and re-verify
993 // it.
994 //
995 // 2. Verify the signature as soon as it's received and don't checkpoint the
996 // blob and the signed sha-256 context.
997 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800998 string(signatures_message_data_.begin(),
999 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001000 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001001 // The hash of all data consumed so far should be verified against the signed
1002 // hash.
1003 signed_hash_context_ = hash_calculator_.GetContext();
1004 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1005 signed_hash_context_))
1006 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001007 LOG(INFO) << "Extracted signature data of size "
1008 << manifest_.signatures_size() << " at "
1009 << manifest_.signatures_offset();
1010 return true;
1011}
1012
David Zeuthene7f89172013-10-31 10:21:04 -07001013bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1014 if (system_state_->hardware()->IsOfficialBuild() ||
1015 utils::FileExists(public_key_path_.c_str()) ||
1016 install_plan_->public_key_rsa.empty())
1017 return false;
1018
1019 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1020 out_tmp_key))
1021 return false;
1022
1023 return true;
1024}
1025
David Zeuthena99981f2013-04-29 13:42:47 -07001026ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001027 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001028
Jay Srinivasanf4318702012-09-24 11:56:24 -07001029 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001030 if (install_plan_->hash_checks_mandatory) {
1031 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001032 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001033 }
1034
1035 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -07001036 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001037 SendUmaStat(ErrorCode::kDownloadMetadataSignatureMissingError);
1038 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001039 }
1040
1041 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001042 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001043 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001044 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001045 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1046 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001047 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001048 }
1049
David Zeuthene7f89172013-10-31 10:21:04 -07001050 // See if we should use the public RSA key in the Omaha response.
1051 base::FilePath path_to_public_key(public_key_path_);
1052 base::FilePath tmp_key;
1053 if (GetPublicKeyFromResponse(&tmp_key))
1054 path_to_public_key = tmp_key;
1055 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1056 if (tmp_key.empty())
1057 tmp_key_remover.set_should_remove(false);
1058
1059 LOG(INFO) << "Verifying metadata hash signature using public key: "
1060 << path_to_public_key.value();
1061
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001062 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001063 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1064 path_to_public_key.value(),
1065 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001066 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001067 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001068 }
1069
Jay Srinivasanf4318702012-09-24 11:56:24 -07001070 OmahaHashCalculator metadata_hasher;
1071 metadata_hasher.Update(metadata, metadata_size);
1072 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001073 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001074 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001075 }
1076
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001077 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001078 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001079 if (calculated_metadata_hash.empty()) {
1080 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001081 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001082 }
1083
Jay Srinivasanf4318702012-09-24 11:56:24 -07001084 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001085 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001086 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001087 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001088 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001089 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001090 }
1091
David Zeuthenbc27aac2013-11-26 11:17:48 -08001092 // The autoupdate_CatchBadSignatures test checks for this string in
1093 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001094 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001095 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001096}
1097
Gilad Arnold21504f02013-05-24 08:51:22 -07001098ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001099 // Perform assorted checks to sanity check the manifest, make sure it
1100 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001101 //
1102 // TODO(garnold) in general, the presence of an old partition hash should be
1103 // the sole indicator for a delta update, as we would generally like update
1104 // payloads to be self contained and not assume an Omaha response to tell us
1105 // that. However, since this requires some massive reengineering of the update
1106 // flow (making filesystem copying happen conditionally only *after*
1107 // downloading and parsing of the update manifest) we'll put it off for now.
1108 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001109 if (install_plan_->is_full_update) {
1110 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1111 LOG(ERROR) << "Purported full payload contains old partition "
1112 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001113 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001114 }
1115
1116 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1117 LOG(ERROR) << "Manifest contains minor version "
1118 << manifest_.minor_version()
1119 << ", but all full payloads should have version "
1120 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001121 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001122 }
1123 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001124 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001125 LOG(ERROR) << "Manifest contains minor version "
1126 << manifest_.minor_version()
1127 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001128 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001129 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001130 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001131 }
1132
1133 // TODO(garnold) we should be adding more and more manifest checks, such as
1134 // partition boundaries etc (see chromium-os:37661).
1135
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001136 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001137}
1138
David Zeuthena99981f2013-04-29 13:42:47 -07001139ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001140 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001141
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001142 if (!operation.data_sha256_hash().size()) {
1143 if (!operation.data_length()) {
1144 // Operations that do not have any data blob won't have any operation hash
1145 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001146 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001147 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001148 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001149 }
1150
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001151 // No hash is present for an operation that has data blobs. This shouldn't
1152 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001153 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001154 // hashes. So if it happens it means either we've turned operation hash
1155 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001156 // One caveat though: The last operation is a dummy signature operation
1157 // that doesn't have a hash at the time the manifest is created. So we
1158 // should not complaint about that operation. This operation can be
1159 // recognized by the fact that it's offset is mentioned in the manifest.
1160 if (manifest_.signatures_offset() &&
1161 manifest_.signatures_offset() == operation.data_offset()) {
1162 LOG(INFO) << "Skipping hash verification for signature operation "
1163 << next_operation_num_ + 1;
1164 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001165 if (install_plan_->hash_checks_mandatory) {
1166 LOG(ERROR) << "Missing mandatory operation hash for operation "
1167 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001168 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001169 }
1170
1171 // For non-mandatory cases, just send a UMA stat.
1172 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1173 << " as there's no operation hash in manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001174 SendUmaStat(ErrorCode::kDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001175 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001176 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001177 }
1178
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001179 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001180 expected_op_hash.assign(operation.data_sha256_hash().data(),
1181 (operation.data_sha256_hash().data() +
1182 operation.data_sha256_hash().size()));
1183
1184 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001185 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001186 if (!operation_hasher.Finalize()) {
1187 LOG(ERROR) << "Unable to compute actual hash of operation "
1188 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001189 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001190 }
1191
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001192 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001193 if (calculated_op_hash != expected_op_hash) {
1194 LOG(ERROR) << "Hash verification failed for operation "
1195 << next_operation_num_ << ". Expected hash = ";
1196 utils::HexDumpVector(expected_op_hash);
1197 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1198 << " bytes at offset: " << operation.data_offset() << " = ";
1199 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001200 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001201 }
1202
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001203 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001204}
1205
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001206#define TEST_AND_RETURN_VAL(_retval, _condition) \
1207 do { \
1208 if (!(_condition)) { \
1209 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1210 return _retval; \
1211 } \
1212 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001213
David Zeuthena99981f2013-04-29 13:42:47 -07001214ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001215 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001216 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001217
1218 // See if we should use the public RSA key in the Omaha response.
1219 base::FilePath path_to_public_key(public_key_path_);
1220 base::FilePath tmp_key;
1221 if (GetPublicKeyFromResponse(&tmp_key))
1222 path_to_public_key = tmp_key;
1223 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1224 if (tmp_key.empty())
1225 tmp_key_remover.set_should_remove(false);
1226
1227 LOG(INFO) << "Verifying payload using public key: "
1228 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001229
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001230 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001231 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001232 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001233 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001234
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001235 // Verifies the payload hash.
1236 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001237 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001238 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001239 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001240 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001241
Darin Petkov437adc42010-10-07 13:12:24 -07001242 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001243 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001244 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001245 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001246 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001247 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001248 !signatures_message_data_.empty());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001249 chromeos::Blob signed_hash_data;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Alex Deymo923d8fa2014-07-15 17:58:51 -07001251 PayloadVerifier::VerifySignature(
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001252 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001253 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001254 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001255 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001256 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001257 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001258 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001259 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001260 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001261 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001262 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001263 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001264 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001265 // The autoupdate_CatchBadSignatures test checks for this string
1266 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001267 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001268 "Attached Signature:";
1269 utils::HexDumpVector(signed_hash_data);
1270 LOG(ERROR) << "Computed Signature:";
1271 utils::HexDumpVector(hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001272 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001273 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001274
David Zeuthene7f89172013-10-31 10:21:04 -07001275 LOG(INFO) << "Payload hash matches value in payload.";
1276
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001277 // At this point, we are guaranteed to have downloaded a full payload, i.e
1278 // the one whose size matches the size mentioned in Omaha response. If any
1279 // errors happen after this, it's likely a problem with the payload itself or
1280 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001281 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001282 system_state_->payload_state()->DownloadComplete();
1283
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001284 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001285}
1286
Darin Petkov3aefa862010-12-07 14:45:00 -08001287bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001288 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001289 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001290 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001291 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1292 manifest_.has_new_kernel_info() &&
1293 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001294 *kernel_size = manifest_.new_kernel_info().size();
1295 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001296 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1297 manifest_.new_kernel_info().hash().end());
1298 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1299 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001300 kernel_hash->swap(new_kernel_hash);
1301 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001302 return true;
1303}
1304
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001305namespace {
1306void LogVerifyError(bool is_kern,
1307 const string& local_hash,
1308 const string& expected_hash) {
1309 const char* type = is_kern ? "kernel" : "rootfs";
1310 LOG(ERROR) << "This is a server-side error due to "
1311 << "mismatched delta update image!";
1312 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1313 << "update that must be applied over a " << type << " with "
1314 << "a specific checksum, but the " << type << " we're starting "
1315 << "with doesn't have that checksum! This means that "
1316 << "the delta I've been given doesn't match my existing "
1317 << "system. The " << type << " partition I have has hash: "
1318 << local_hash << " but the update expected me to have "
1319 << expected_hash << " .";
1320 if (is_kern) {
1321 LOG(INFO) << "To get the checksum of a kernel partition on a "
1322 << "booted machine, run this command (change /dev/sda2 "
1323 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1324 << "openssl dgst -sha256 -binary | openssl base64";
1325 } else {
1326 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1327 << "booted machine, run this command (change /dev/sda3 "
1328 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1329 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1330 << "| sed 's/[^0-9]*//') / 256 )) | "
1331 << "openssl dgst -sha256 -binary | openssl base64";
1332 }
1333 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1334 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1335}
1336
1337string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001338 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001339}
1340} // namespace
1341
Darin Petkov698d0412010-10-13 10:59:44 -07001342bool DeltaPerformer::VerifySourcePartitions() {
1343 LOG(INFO) << "Verifying source partitions.";
1344 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001345 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001346 if (manifest_.has_old_kernel_info()) {
1347 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001348 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001349 !install_plan_->source_kernel_hash.empty() &&
1350 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1351 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001352 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001353 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001354 if (!valid) {
1355 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001356 StringForHashBytes(
1357 install_plan_->source_kernel_hash.data(),
1358 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001359 StringForHashBytes(info.hash().data(),
1360 info.hash().size()));
1361 }
1362 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001363 }
1364 if (manifest_.has_old_rootfs_info()) {
1365 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001366 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001367 !install_plan_->source_rootfs_hash.empty() &&
1368 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1369 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001370 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001371 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001372 if (!valid) {
1373 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001374 StringForHashBytes(
1375 install_plan_->source_rootfs_hash.data(),
1376 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001377 StringForHashBytes(info.hash().data(),
1378 info.hash().size()));
1379 }
1380 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001381 }
1382 return true;
1383}
1384
Gilad Arnolddaa27402014-01-23 11:56:17 -08001385void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001386 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001387 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001388 buffer_offset_ += buffer_.size();
1389
1390 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001391 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001392
1393 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001394 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001395}
1396
Darin Petkov0406e402010-10-06 21:33:11 -07001397bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1398 string update_check_response_hash) {
1399 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001400 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1401 next_operation != kUpdateStateOperationInvalid &&
1402 next_operation > 0))
1403 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001404
1405 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001406 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1407 !interrupted_hash.empty() &&
1408 interrupted_hash == update_check_response_hash))
1409 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001410
Darin Petkov61426142010-10-08 11:04:55 -07001411 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001412 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1413 && resumed_update_failures > kMaxResumedUpdateFailures))
1414 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001415
Darin Petkov0406e402010-10-06 21:33:11 -07001416 // Sanity check the rest.
1417 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001418 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1419 next_data_offset >= 0))
1420 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001421
Darin Petkov437adc42010-10-07 13:12:24 -07001422 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001423 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1424 !sha256_context.empty()))
1425 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001426
1427 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001428 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1429 manifest_metadata_size > 0))
1430 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001431
1432 return true;
1433}
1434
Darin Petkov9b230572010-10-08 10:20:09 -07001435bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001436 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1437 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001438 if (!quick) {
1439 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1440 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001441 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001442 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1443 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001444 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001445 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001446 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001447 }
Darin Petkov73058b42010-10-06 16:32:19 -07001448 return true;
1449}
1450
1451bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001452 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001453 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001454 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001455 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001456 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001457 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001458 hash_calculator_.GetContext()));
1459 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1460 buffer_offset_));
1461 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001462
1463 if (next_operation_num_ < num_total_operations_) {
1464 const bool is_kernel_partition =
1465 next_operation_num_ >= num_rootfs_operations_;
1466 const DeltaArchiveManifest_InstallOperation &op =
1467 is_kernel_partition ?
1468 manifest_.kernel_install_operations(
1469 next_operation_num_ - num_rootfs_operations_) :
1470 manifest_.install_operations(next_operation_num_);
1471 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1472 op.data_length()));
1473 } else {
1474 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1475 0));
1476 }
Darin Petkov0406e402010-10-06 21:33:11 -07001477 }
Darin Petkov73058b42010-10-06 16:32:19 -07001478 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1479 next_operation_num_));
1480 return true;
1481}
1482
Darin Petkov9b230572010-10-08 10:20:09 -07001483bool DeltaPerformer::PrimeUpdateState() {
1484 CHECK(manifest_valid_);
1485 block_size_ = manifest_.block_size();
1486
1487 int64_t next_operation = kUpdateStateOperationInvalid;
1488 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1489 next_operation == kUpdateStateOperationInvalid ||
1490 next_operation <= 0) {
1491 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001492 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001493 return true;
1494 }
1495 next_operation_num_ = next_operation;
1496
1497 // Resuming an update -- load the rest of the update state.
1498 int64_t next_data_offset = -1;
1499 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1500 &next_data_offset) &&
1501 next_data_offset >= 0);
1502 buffer_offset_ = next_data_offset;
1503
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001504 // The signed hash context and the signature blob may be empty if the
1505 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001506 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1507 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001508 string signature_blob;
1509 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1510 signatures_message_data_.assign(signature_blob.begin(),
1511 signature_blob.end());
1512 }
Darin Petkov9b230572010-10-08 10:20:09 -07001513
1514 string hash_context;
1515 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1516 &hash_context) &&
1517 hash_calculator_.SetContext(hash_context));
1518
1519 int64_t manifest_metadata_size = 0;
1520 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1521 &manifest_metadata_size) &&
1522 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001523 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001524
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001525 // Advance the download progress to reflect what doesn't need to be
1526 // re-downloaded.
1527 total_bytes_received_ += buffer_offset_;
1528
Darin Petkov61426142010-10-08 11:04:55 -07001529 // Speculatively count the resume as a failure.
1530 int64_t resumed_update_failures;
1531 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1532 resumed_update_failures++;
1533 } else {
1534 resumed_update_failures = 1;
1535 }
1536 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001537 return true;
1538}
1539
David Zeuthena99981f2013-04-29 13:42:47 -07001540void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001541 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001542}
1543
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001544} // namespace chromeos_update_engine