blob: 00718341e04d1a3327bba458d132c068dba73ade [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070016
17#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070018
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include <endian.h>
20#include <errno.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070021
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include <algorithm>
23#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070024#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070025#include <string>
26#include <vector>
27
Ben Chan06c76a42014-09-05 08:21:06 -070028#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070029#include <base/format_macros.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070030#include <base/strings/string_util.h>
31#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080032#include <chromeos/data_encoding.h>
Alex Deymo05322872015-09-30 09:50:24 -070033#include <chromeos/make_unique_ptr.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070034#include <google/protobuf/repeated_field.h>
35
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070036#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070037#include "update_engine/constants.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070039#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080040#if USE_MTD
41#include "update_engine/mtd_file_descriptor.h"
42#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070043#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080044#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070045#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070046#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070047#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070048#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070049#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070050
Alex Deymo161c4a12014-05-16 15:56:21 -070051using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070052using std::min;
53using std::string;
54using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070055
56namespace chromeos_update_engine {
57
Jay Srinivasanf4318702012-09-24 11:56:24 -070058const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
59const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Don Garrett4d039442013-10-28 18:40:06 -070060const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Allie Wood6eeec902015-04-15 10:40:52 -070061const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 2;
Don Garrett4d039442013-10-28 18:40:06 -070062
Gilad Arnold8a86fa52013-01-15 12:35:05 -080063const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
64const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
65const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
66const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080067
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070068namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070069const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070070const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080071#if USE_MTD
72const int kUbiVolumeAttachTimeout = 5 * 60;
73#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080074
75FileDescriptorPtr CreateFileDescriptor(const char* path) {
76 FileDescriptorPtr ret;
77#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080078 if (strstr(path, "/dev/ubi") == path) {
79 if (!UbiFileDescriptor::IsUbi(path)) {
80 // The volume might not have been attached at boot time.
81 int volume_no;
82 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
83 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
84 }
85 }
86 if (UbiFileDescriptor::IsUbi(path)) {
87 LOG(INFO) << path << " is a UBI device.";
88 ret.reset(new UbiFileDescriptor);
89 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080090 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080091 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080092 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080093 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080094 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080095#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080096 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080097#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070098 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080099#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800100 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700101}
102
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800103// Opens path for read/write. On success returns an open FileDescriptor
104// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
105FileDescriptorPtr OpenFile(const char* path, int* err) {
106 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800107 int mode = O_RDWR;
108#if USE_MTD
109 // On NAND devices, we can either read, or write, but not both. So here we
110 // use O_WRONLY.
111 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
112 mode = O_WRONLY;
113 }
114#endif
115 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800116 *err = errno;
117 PLOG(ERROR) << "Unable to open file " << path;
118 return nullptr;
119 }
120 *err = 0;
121 return fd;
122}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700123} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700124
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800125
126// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
127// arithmetic.
128static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
129 return part * norm / total;
130}
131
132void DeltaPerformer::LogProgress(const char* message_prefix) {
133 // Format operations total count and percentage.
134 string total_operations_str("?");
135 string completed_percentage_str("");
136 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700137 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800138 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
139 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700140 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700141 IntRatio(next_operation_num_, num_total_operations_,
142 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800143 }
144
145 // Format download total count and percentage.
146 size_t payload_size = install_plan_->payload_size;
147 string payload_size_str("?");
148 string downloaded_percentage_str("");
149 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700150 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800151 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
152 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700153 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700154 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800155 }
156
157 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
158 << "/" << total_operations_str << " operations"
159 << completed_percentage_str << ", " << total_bytes_received_
160 << "/" << payload_size_str << " bytes downloaded"
161 << downloaded_percentage_str << ", overall progress "
162 << overall_progress_ << "%";
163}
164
165void DeltaPerformer::UpdateOverallProgress(bool force_log,
166 const char* message_prefix) {
167 // Compute our download and overall progress.
168 unsigned new_overall_progress = 0;
169 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
170 progress_weight_dont_add_up);
171 // Only consider download progress if its total size is known; otherwise
172 // adjust the operations weight to compensate for the absence of download
173 // progress. Also, make sure to cap the download portion at
174 // kProgressDownloadWeight, in case we end up downloading more than we
175 // initially expected (this indicates a problem, but could generally happen).
176 // TODO(garnold) the correction of operations weight when we do not have the
177 // total payload size, as well as the conditional guard below, should both be
178 // eliminated once we ensure that the payload_size in the install plan is
179 // always given and is non-zero. This currently isn't the case during unit
180 // tests (see chromium-os:37969).
181 size_t payload_size = install_plan_->payload_size;
182 unsigned actual_operations_weight = kProgressOperationsWeight;
183 if (payload_size)
184 new_overall_progress += min(
185 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
186 kProgressDownloadWeight)),
187 kProgressDownloadWeight);
188 else
189 actual_operations_weight += kProgressDownloadWeight;
190
191 // Only add completed operations if their total number is known; we definitely
192 // expect an update to have at least one operation, so the expectation is that
193 // this will eventually reach |actual_operations_weight|.
194 if (num_total_operations_)
195 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
196 actual_operations_weight);
197
198 // Progress ratio cannot recede, unless our assumptions about the total
199 // payload size, total number of operations, or the monotonicity of progress
200 // is breached.
201 if (new_overall_progress < overall_progress_) {
202 LOG(WARNING) << "progress counter receded from " << overall_progress_
203 << "% down to " << new_overall_progress << "%; this is a bug";
204 force_log = true;
205 }
206 overall_progress_ = new_overall_progress;
207
208 // Update chunk index, log as needed: if forced by called, or we completed a
209 // progress chunk, or a timeout has expired.
210 base::Time curr_time = base::Time::Now();
211 unsigned curr_progress_chunk =
212 overall_progress_ * kProgressLogMaxChunks / 100;
213 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
214 curr_time > forced_progress_log_time_) {
215 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
216 LogProgress(message_prefix);
217 }
218 last_progress_chunk_ = curr_progress_chunk;
219}
220
221
Gilad Arnoldfe133932014-01-14 12:25:50 -0800222size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
223 size_t max) {
224 const size_t count = *count_p;
225 if (!count)
226 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700227 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800228 const char* bytes_start = *bytes_p;
229 const char* bytes_end = bytes_start + read_len;
230 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
231 *bytes_p = bytes_end;
232 *count_p = count - read_len;
233 return read_len;
234}
235
236
237bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
238 ErrorCode* error) {
239 if (op_result)
240 return true;
241
242 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
243 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700244 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800245 return false;
246}
247
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700248int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700249 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800250 fd_ = OpenFile(path, &err);
251 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700252 path_ = path;
253 return -err;
254}
255
256bool DeltaPerformer::OpenKernel(const char* kernel_path) {
257 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800258 kernel_fd_ = OpenFile(kernel_path, &err);
259 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700260 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800261 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700262}
263
Alex Deymo1beda782015-06-07 23:01:25 +0200264bool DeltaPerformer::OpenSourceRootfs(const string& source_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800265 int err;
266 source_fd_ = OpenFile(source_path.c_str(), &err);
267 return static_cast<bool>(source_fd_);
268}
269
Alex Deymo1beda782015-06-07 23:01:25 +0200270bool DeltaPerformer::OpenSourceKernel(const string& source_kernel_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800271 int err;
272 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
273 return static_cast<bool>(source_kernel_fd_);
274}
275
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700276int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700277 int err = 0;
Sen Jiang2d528b42015-09-25 11:18:12 -0700278 if (kernel_fd_ && !kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700279 err = errno;
280 PLOG(ERROR) << "Unable to close kernel fd:";
281 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800282 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700283 err = errno;
284 PLOG(ERROR) << "Unable to close rootfs fd:";
285 }
Allie Woodfdf00512015-03-02 13:34:55 -0800286 if (source_fd_ && !source_fd_->Close()) {
287 err = errno;
288 PLOG(ERROR) << "Unable to close source rootfs fd:";
289 }
290 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
291 err = errno;
292 PLOG(ERROR) << "Unable to close source kernel fd:";
293 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700294 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800295 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800296 kernel_fd_.reset();
297 source_fd_.reset();
298 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700299 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800300 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700301 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
302 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800303 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800304 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700305 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700306}
307
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700308namespace {
309
310void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800311 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800312 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
313 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700314}
315
316void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
317 if (manifest.has_old_kernel_info())
318 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
319 if (manifest.has_old_rootfs_info())
320 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
321 if (manifest.has_new_kernel_info())
322 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
323 if (manifest.has_new_rootfs_info())
324 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
325}
326
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700327} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700328
Don Garrett4d039442013-10-28 18:40:06 -0700329uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800330 // Manifest size is stored right after the magic string and the version.
331 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700332}
333
Jay Srinivasanf4318702012-09-24 11:56:24 -0700334uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800335 // Manifest size is stored right after the magic string and the version.
336 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700337}
338
339uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800340 // Actual manifest begins right after the manifest size field.
341 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700342}
343
Gilad Arnoldfe133932014-01-14 12:25:50 -0800344uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800345 return metadata_size_;
346}
347
Allie Woodfdf00512015-03-02 13:34:55 -0800348uint32_t DeltaPerformer::GetMinorVersion() const {
349 if (manifest_.has_minor_version()) {
350 return manifest_.minor_version();
351 } else {
352 return (install_plan_->is_full_update ?
353 kFullPayloadMinorVersion :
354 kSupportedMinorPayloadVersion);
355 }
356}
357
Gilad Arnolddaa27402014-01-23 11:56:17 -0800358bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
359 if (!manifest_parsed_)
360 return false;
361 *out_manifest_p = manifest_;
362 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800363}
364
Jay Srinivasanf4318702012-09-24 11:56:24 -0700365
Darin Petkov9574f7e2011-01-13 10:48:12 -0800366DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800367 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700368 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700369 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800370 uint64_t manifest_size = (metadata_size_ ?
371 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700372
Gilad Arnoldfe133932014-01-14 12:25:50 -0800373 if (!manifest_size) {
374 // Ensure we have data to cover the payload header.
375 if (payload.size() < manifest_offset)
376 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700377
Gilad Arnoldfe133932014-01-14 12:25:50 -0800378 // Validate the magic string.
379 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
380 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700381 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800382 return kMetadataParseError;
383 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800384
385 // Extract the payload version from the metadata.
386 uint64_t major_payload_version;
387 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
388 major_payload_version_size_mismatch);
389 memcpy(&major_payload_version,
390 &payload[GetVersionOffset()],
391 kDeltaVersionSize);
392 // switch big endian to host
393 major_payload_version = be64toh(major_payload_version);
394
395 if (major_payload_version != kSupportedMajorPayloadVersion) {
396 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
397 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700398 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800399 return kMetadataParseError;
400 }
401
402 // Next, parse the manifest size.
403 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
404 manifest_size_size_mismatch);
405 memcpy(&manifest_size,
406 &payload[GetManifestSizeOffset()],
407 kDeltaManifestSizeSize);
408 manifest_size = be64toh(manifest_size); // switch big endian to host
409
410 // If the metadata size is present in install plan, check for it immediately
411 // even before waiting for that many number of bytes to be downloaded in the
412 // payload. This will prevent any attack which relies on us downloading data
413 // beyond the expected metadata size.
414 metadata_size_ = manifest_offset + manifest_size;
415 if (install_plan_->hash_checks_mandatory) {
416 if (install_plan_->metadata_size != metadata_size_) {
417 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
418 << install_plan_->metadata_size
419 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700420 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800421 return kMetadataParseError;
422 }
423 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700424 }
425
426 // Now that we have validated the metadata size, we should wait for the full
427 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800428 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800429 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700430
431 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700432 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700433 // that we just log once (instead of logging n times) if it takes n
434 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800435 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700436 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800437 } else {
438 // For mandatory-cases, we'd have already returned a kMetadataParseError
439 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
440 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
441 << install_plan_->metadata_size
442 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800443 << "Trusting metadata size in payload = " << metadata_size_;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800444 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700445
Jay Srinivasanf4318702012-09-24 11:56:24 -0700446 // We have the full metadata in |payload|. Verify its integrity
447 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800448 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700449 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800450 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800451 // The autoupdate_CatchBadSignatures test checks for this string
452 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800453 LOG(ERROR) << "Mandatory metadata signature validation failed";
454 return kMetadataParseError;
455 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700456
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800457 // For non-mandatory cases, just send a UMA stat.
458 LOG(WARNING) << "Ignoring metadata signature validation failures";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700459 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700460 }
461
Gilad Arnolddaa27402014-01-23 11:56:17 -0800462 // The payload metadata is deemed valid, it's safe to parse the protobuf.
463 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800464 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700465 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800466 return kMetadataParseError;
467 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800468
469 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800470 return kMetadataParseSuccess;
471}
472
Don Garrette410e0f2011-11-10 15:39:01 -0800473// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800474// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700475// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800476bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700477 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700478
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700479 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800480 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800481
482 // Update the total byte downloaded count and the progress logs.
483 total_bytes_received_ += count;
484 UpdateOverallProgress(false, "Completed ");
485
Gilad Arnoldfe133932014-01-14 12:25:50 -0800486 while (!manifest_valid_) {
487 // Read data up to the needed limit; this is either the payload header size,
488 // or the full metadata size (once it becomes known).
489 const bool do_read_header = !metadata_size_;
490 CopyDataToBuffer(&c_bytes, &count,
491 (do_read_header ? GetManifestOffset() :
492 metadata_size_));
493
Gilad Arnolddaa27402014-01-23 11:56:17 -0800494 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700495 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800496 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800497 if (result == kMetadataParseInsufficientData) {
498 // If we just processed the header, make an attempt on the manifest.
499 if (do_read_header && metadata_size_)
500 continue;
501
Don Garrette410e0f2011-11-10 15:39:01 -0800502 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800503 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700504
505 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700506 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700507 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800508 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700509
Gilad Arnoldfe133932014-01-14 12:25:50 -0800510 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800511 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700512 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800513 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700514 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700515
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700516 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700517 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700518 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700519 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800520 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700521 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800522
Allie Woodfdf00512015-03-02 13:34:55 -0800523 // Open source fds if we have a delta payload with minor version 2.
524 if (!install_plan_->is_full_update &&
525 GetMinorVersion() == kSourceMinorPayloadVersion) {
526 if (!OpenSourceRootfs(install_plan_->source_path)) {
527 LOG(ERROR) << "Unable to open source rootfs partition file "
528 << install_plan_->source_path;
529 Close();
530 return false;
531 }
532 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
533 LOG(ERROR) << "Unable to open source kernel partition file "
534 << install_plan_->kernel_source_path;
535 Close();
536 return false;
537 }
538 }
539
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800540 num_rootfs_operations_ = manifest_.install_operations_size();
541 num_total_operations_ =
542 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
543 if (next_operation_num_ > 0)
544 UpdateOverallProgress(true, "Resuming after ");
545 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700546 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800547
548 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700549 // Check if we should cancel the current attempt for any reason.
550 // In this case, *error will have already been populated with the reason
551 // why we're cancelling.
552 if (system_state_->update_attempter()->ShouldCancel(error))
553 return false;
554
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800555 const bool is_kernel_partition =
556 (next_operation_num_ >= num_rootfs_operations_);
Alex Deymoa12ee112015-08-12 22:19:32 -0700557 const InstallOperation& op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800558 is_kernel_partition ?
Alex Deymoa12ee112015-08-12 22:19:32 -0700559 manifest_.kernel_install_operations(next_operation_num_ -
560 num_rootfs_operations_) :
561 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800562
563 CopyDataToBuffer(&c_bytes, &count, op.data_length());
564
565 // Check whether we received all of the next operation's data payload.
566 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700567 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700568
Jay Srinivasanf4318702012-09-24 11:56:24 -0700569 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700570 // Otherwise, keep the old behavior. This serves as a knob to disable
571 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800572 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
573 // we would have already failed in ParsePayloadMetadata method and thus not
574 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700575 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700576 // Note: Validate must be called only if CanPerformInstallOperation is
577 // called. Otherwise, we might be failing operations before even if there
578 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800579 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700580 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800581 if (install_plan_->hash_checks_mandatory) {
582 LOG(ERROR) << "Mandatory operation hash check failed";
583 return false;
584 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700585
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800586 // For non-mandatory cases, just send a UMA stat.
587 LOG(WARNING) << "Ignoring operation validation errors";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700588 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700589 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700590 }
591
Darin Petkov45580e42010-10-08 14:02:40 -0700592 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700593 ScopedTerminatorExitUnblocker exit_unblocker =
594 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800595
596 bool op_result;
Alex Deymoa12ee112015-08-12 22:19:32 -0700597 if (op.type() == InstallOperation::REPLACE ||
598 op.type() == InstallOperation::REPLACE_BZ)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800599 op_result = HandleOpResult(
600 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700601 else if (op.type() == InstallOperation::MOVE)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800602 op_result = HandleOpResult(
603 PerformMoveOperation(op, is_kernel_partition), "move", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700604 else if (op.type() == InstallOperation::BSDIFF)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800605 op_result = HandleOpResult(
606 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700607 else if (op.type() == InstallOperation::SOURCE_COPY)
Allie Wood9f6f0a52015-03-30 11:25:47 -0700608 op_result =
609 HandleOpResult(PerformSourceCopyOperation(op, is_kernel_partition),
610 "source_copy", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700611 else if (op.type() == InstallOperation::SOURCE_BSDIFF)
Allie Wood9f6f0a52015-03-30 11:25:47 -0700612 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(
Alex Deymoa12ee112015-08-12 22:19:32 -0700633 const chromeos_update_engine::InstallOperation& 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.
Alex Deymoa12ee112015-08-12 22:19:32 -0700636 if (operation.type() == InstallOperation::MOVE ||
637 operation.type() == InstallOperation::SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700638 return true;
639
640 // See if we have the entire data blob in the buffer
641 if (operation.data_offset() < buffer_offset_) {
642 LOG(ERROR) << "we threw away data it seems?";
643 return false;
644 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700645
Gilad Arnoldfe133932014-01-14 12:25:50 -0800646 return (operation.data_offset() + operation.data_length() <=
647 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700648}
649
Alex Deymoa12ee112015-08-12 22:19:32 -0700650bool DeltaPerformer::PerformReplaceOperation(const InstallOperation& operation,
651 bool is_kernel_partition) {
652 CHECK(operation.type() == InstallOperation::REPLACE ||
653 operation.type() == InstallOperation::REPLACE_BZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654
655 // Since we delete data off the beginning of the buffer as we use it,
656 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700657 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
658 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700659
Darin Petkov437adc42010-10-07 13:12:24 -0700660 // Extract the signature message if it's in this operation.
661 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700662
Alex Deymo05322872015-09-30 09:50:24 -0700663 // Setup the ExtentWriter stack based on the operation type.
664 std::unique_ptr<ExtentWriter> writer =
665 chromeos::make_unique_ptr(new ZeroPadExtentWriter(
666 chromeos::make_unique_ptr(new DirectExtentWriter())));
Darin Petkovd7061ab2010-10-06 14:37:09 -0700667
Alex Deymo05322872015-09-30 09:50:24 -0700668 if (operation.type() == InstallOperation::REPLACE_BZ)
669 writer.reset(new BzipExtentWriter(std::move(writer)));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700670
671 // Create a vector of extents to pass to the ExtentWriter.
672 vector<Extent> extents;
673 for (int i = 0; i < operation.dst_extents_size(); i++) {
674 extents.push_back(operation.dst_extents(i));
675 }
676
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800677 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700678
679 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800680 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700681 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700682
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700683 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800684 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700685 return true;
686}
687
Alex Deymoa12ee112015-08-12 22:19:32 -0700688bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation,
689 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700690 // Calculate buffer size. Note, this function doesn't do a sliding
691 // window to copy in case the source and destination blocks overlap.
692 // If we wanted to do a sliding window, we could program the server
693 // to generate deltas that effectively did a sliding window.
694
695 uint64_t blocks_to_read = 0;
696 for (int i = 0; i < operation.src_extents_size(); i++)
697 blocks_to_read += operation.src_extents(i).num_blocks();
698
699 uint64_t blocks_to_write = 0;
700 for (int i = 0; i < operation.dst_extents_size(); i++)
701 blocks_to_write += operation.dst_extents(i).num_blocks();
702
703 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800704 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700705
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800706 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700707
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700708 // Read in bytes.
709 ssize_t bytes_read = 0;
710 for (int i = 0; i < operation.src_extents_size(); i++) {
711 ssize_t bytes_read_this_iteration = 0;
712 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200713 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700714 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
715 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
716 &buf[bytes_read],
717 bytes,
718 extent.start_block() * block_size_,
719 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700720 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200721 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700722 bytes_read += bytes_read_this_iteration;
723 }
724
725 // Write bytes out.
726 ssize_t bytes_written = 0;
727 for (int i = 0; i < operation.dst_extents_size(); i++) {
728 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200729 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700730 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
731 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
732 &buf[bytes_written],
733 bytes,
734 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200735 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700736 }
737 DCHECK_EQ(bytes_written, bytes_read);
738 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
739 return true;
740}
741
Allie Wood9f6f0a52015-03-30 11:25:47 -0700742namespace {
743
744// Takes |extents| and fills an empty vector |blocks| with a block index for
745// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
746void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
747 vector<uint64_t>* blocks) {
748 for (Extent ext : extents) {
749 for (uint64_t j = 0; j < ext.num_blocks(); j++)
750 blocks->push_back(ext.start_block() + j);
751 }
752}
753
754// Takes |extents| and returns the number of blocks in those extents.
755uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
756 uint64_t sum = 0;
757 for (Extent ext : extents) {
758 sum += ext.num_blocks();
759 }
760 return sum;
761}
762
763} // namespace
764
765bool DeltaPerformer::PerformSourceCopyOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700766 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700767 bool is_kernel_partition) {
768 if (operation.has_src_length())
769 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
770 if (operation.has_dst_length())
771 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
772
773 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
774 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
775 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
776
777 // Create vectors of all the individual src/dst blocks.
778 vector<uint64_t> src_blocks;
779 vector<uint64_t> dst_blocks;
780 ExtentsToBlocks(operation.src_extents(), &src_blocks);
781 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
782 DCHECK_EQ(src_blocks.size(), blocks_to_read);
783 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
784
785 FileDescriptorPtr src_fd =
786 is_kernel_partition ? source_kernel_fd_ : source_fd_;
787 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
788
789 chromeos::Blob buf(block_size_);
790 ssize_t bytes_read = 0;
791 // Read/write one block at a time.
792 for (uint64_t i = 0; i < blocks_to_read; i++) {
793 ssize_t bytes_read_this_iteration = 0;
794 uint64_t src_block = src_blocks[i];
795 uint64_t dst_block = dst_blocks[i];
796
797 // Read in bytes.
798 TEST_AND_RETURN_FALSE(
799 utils::PReadAll(src_fd,
800 buf.data(),
801 block_size_,
802 src_block * block_size_,
803 &bytes_read_this_iteration));
804
805 // Write bytes out.
806 TEST_AND_RETURN_FALSE(
807 utils::PWriteAll(dst_fd,
808 buf.data(),
809 block_size_,
810 dst_block * block_size_));
811
812 bytes_read += bytes_read_this_iteration;
813 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
814 static_cast<ssize_t>(block_size_));
815 }
816 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
817 return true;
818}
819
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700820bool DeltaPerformer::ExtentsToBsdiffPositionsString(
821 const RepeatedPtrField<Extent>& extents,
822 uint64_t block_size,
823 uint64_t full_length,
824 string* positions_string) {
825 string ret;
826 uint64_t length = 0;
827 for (int i = 0; i < extents.size(); i++) {
828 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700829 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700830 uint64_t this_length = min(full_length - length,
831 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700832 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700833 length += this_length;
834 }
835 TEST_AND_RETURN_FALSE(length == full_length);
836 if (!ret.empty())
837 ret.resize(ret.size() - 1); // Strip trailing comma off
838 *positions_string = ret;
839 return true;
840}
841
Alex Deymoa12ee112015-08-12 22:19:32 -0700842bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation,
843 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700844 // Since we delete data off the beginning of the buffer as we use it,
845 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700846 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
847 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700848
849 string input_positions;
850 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
851 block_size_,
852 operation.src_length(),
853 &input_positions));
854 string output_positions;
855 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
856 block_size_,
857 operation.dst_length(),
858 &output_positions));
859
860 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -0700861 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700862 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700863 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700864 ScopedPathUnlinker path_unlinker(temp_filename);
865 {
866 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
867 ScopedFdCloser fd_closer(&fd);
868 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800869 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700870 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700871
Darin Petkov7f2ec752013-04-03 14:45:19 +0200872 // Update the buffer to release the patch data memory as soon as the patch
873 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800874 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200875
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800876 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700877 vector<string> cmd{kBspatchPath, path, path, temp_filename,
878 input_positions, output_positions};
879
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700880 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700881 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700882 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
883 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700884 TEST_AND_RETURN_FALSE(return_code == 0);
885
886 if (operation.dst_length() % block_size_) {
887 // Zero out rest of final block.
888 // TODO(adlr): build this into bspatch; it's more efficient that way.
889 const Extent& last_extent =
890 operation.dst_extents(operation.dst_extents_size() - 1);
891 const uint64_t end_byte =
892 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
893 const uint64_t begin_byte =
894 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800895 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800896 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700897 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800898 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700899 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700900 return true;
901}
902
Allie Wood9f6f0a52015-03-30 11:25:47 -0700903bool DeltaPerformer::PerformSourceBsdiffOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700904 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700905 bool is_kernel_partition) {
906 // Since we delete data off the beginning of the buffer as we use it,
907 // the data we need should be exactly at the beginning of the buffer.
908 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
909 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
910 if (operation.has_src_length())
911 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
912 if (operation.has_dst_length())
913 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
914
915 string input_positions;
916 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
917 block_size_,
918 operation.src_length(),
919 &input_positions));
920 string output_positions;
921 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
922 block_size_,
923 operation.dst_length(),
924 &output_positions));
925
926 string temp_filename;
Alex Deymo5aa1c542015-09-18 01:02:33 -0700927 TEST_AND_RETURN_FALSE(utils::MakeTempFile("au_patch.XXXXXX",
Allie Wood9f6f0a52015-03-30 11:25:47 -0700928 &temp_filename,
929 nullptr));
930 ScopedPathUnlinker path_unlinker(temp_filename);
931 {
932 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
933 ScopedFdCloser fd_closer(&fd);
934 TEST_AND_RETURN_FALSE(
935 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
936 }
937
938 // Update the buffer to release the patch data memory as soon as the patch
939 // file is written out.
940 DiscardBuffer(true);
941
942 const string& src_path = is_kernel_partition ?
943 install_plan_->kernel_source_path :
944 install_plan_->source_path;
945 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
946 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
947 input_positions, output_positions};
948
949 int return_code = 0;
950 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700951 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
952 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -0700953 TEST_AND_RETURN_FALSE(return_code == 0);
954 return true;
955}
956
Darin Petkovd7061ab2010-10-06 14:37:09 -0700957bool DeltaPerformer::ExtractSignatureMessage(
Alex Deymoa12ee112015-08-12 22:19:32 -0700958 const InstallOperation& operation) {
959 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -0700960 !manifest_.has_signatures_offset() ||
961 manifest_.signatures_offset() != operation.data_offset()) {
962 return false;
963 }
964 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
965 manifest_.signatures_size() == operation.data_length());
966 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
967 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
968 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700969 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700970 buffer_.begin(),
971 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700972
973 // Save the signature blob because if the update is interrupted after the
974 // download phase we don't go through this path anymore. Some alternatives to
975 // consider:
976 //
977 // 1. On resume, re-download the signature blob from the server and re-verify
978 // it.
979 //
980 // 2. Verify the signature as soon as it's received and don't checkpoint the
981 // blob and the signed sha-256 context.
982 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800983 string(signatures_message_data_.begin(),
984 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700985 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700986 // The hash of all data consumed so far should be verified against the signed
987 // hash.
988 signed_hash_context_ = hash_calculator_.GetContext();
989 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
990 signed_hash_context_))
991 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700992 LOG(INFO) << "Extracted signature data of size "
993 << manifest_.signatures_size() << " at "
994 << manifest_.signatures_offset();
995 return true;
996}
997
David Zeuthene7f89172013-10-31 10:21:04 -0700998bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
999 if (system_state_->hardware()->IsOfficialBuild() ||
1000 utils::FileExists(public_key_path_.c_str()) ||
1001 install_plan_->public_key_rsa.empty())
1002 return false;
1003
1004 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1005 out_tmp_key))
1006 return false;
1007
1008 return true;
1009}
1010
David Zeuthena99981f2013-04-29 13:42:47 -07001011ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001012 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001013
Jay Srinivasanf4318702012-09-24 11:56:24 -07001014 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001015 if (install_plan_->hash_checks_mandatory) {
1016 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001017 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001018 }
1019
Jay Srinivasanf4318702012-09-24 11:56:24 -07001020 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001021 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001022 }
1023
1024 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001025 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001026 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001027 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001028 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1029 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001030 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001031 }
1032
David Zeuthene7f89172013-10-31 10:21:04 -07001033 // See if we should use the public RSA key in the Omaha response.
1034 base::FilePath path_to_public_key(public_key_path_);
1035 base::FilePath tmp_key;
1036 if (GetPublicKeyFromResponse(&tmp_key))
1037 path_to_public_key = tmp_key;
1038 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1039 if (tmp_key.empty())
1040 tmp_key_remover.set_should_remove(false);
1041
1042 LOG(INFO) << "Verifying metadata hash signature using public key: "
1043 << path_to_public_key.value();
1044
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001045 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001046 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1047 path_to_public_key.value(),
1048 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001049 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001050 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001051 }
1052
Jay Srinivasanf4318702012-09-24 11:56:24 -07001053 OmahaHashCalculator metadata_hasher;
1054 metadata_hasher.Update(metadata, metadata_size);
1055 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001056 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001057 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001058 }
1059
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001060 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001061 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001062 if (calculated_metadata_hash.empty()) {
1063 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001064 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001065 }
1066
Jay Srinivasanf4318702012-09-24 11:56:24 -07001067 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001068 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001069 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001070 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001071 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001073 }
1074
David Zeuthenbc27aac2013-11-26 11:17:48 -08001075 // The autoupdate_CatchBadSignatures test checks for this string in
1076 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001077 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001078 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001079}
1080
Gilad Arnold21504f02013-05-24 08:51:22 -07001081ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001082 // Perform assorted checks to sanity check the manifest, make sure it
1083 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001084 //
1085 // TODO(garnold) in general, the presence of an old partition hash should be
1086 // the sole indicator for a delta update, as we would generally like update
1087 // payloads to be self contained and not assume an Omaha response to tell us
1088 // that. However, since this requires some massive reengineering of the update
1089 // flow (making filesystem copying happen conditionally only *after*
1090 // downloading and parsing of the update manifest) we'll put it off for now.
1091 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001092 if (install_plan_->is_full_update) {
1093 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1094 LOG(ERROR) << "Purported full payload contains old partition "
1095 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001096 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001097 }
1098
1099 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1100 LOG(ERROR) << "Manifest contains minor version "
1101 << manifest_.minor_version()
1102 << ", but all full payloads should have version "
1103 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001104 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001105 }
1106 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001107 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001108 LOG(ERROR) << "Manifest contains minor version "
1109 << manifest_.minor_version()
1110 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001111 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001112 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001113 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001114 }
1115
1116 // TODO(garnold) we should be adding more and more manifest checks, such as
1117 // partition boundaries etc (see chromium-os:37661).
1118
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001119 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001120}
1121
David Zeuthena99981f2013-04-29 13:42:47 -07001122ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001123 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001124 if (!operation.data_sha256_hash().size()) {
1125 if (!operation.data_length()) {
1126 // Operations that do not have any data blob won't have any operation hash
1127 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001128 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001129 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001130 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001131 }
1132
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001133 // No hash is present for an operation that has data blobs. This shouldn't
1134 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001135 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001136 // hashes. So if it happens it means either we've turned operation hash
1137 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001138 // One caveat though: The last operation is a dummy signature operation
1139 // that doesn't have a hash at the time the manifest is created. So we
1140 // should not complaint about that operation. This operation can be
1141 // recognized by the fact that it's offset is mentioned in the manifest.
1142 if (manifest_.signatures_offset() &&
1143 manifest_.signatures_offset() == operation.data_offset()) {
1144 LOG(INFO) << "Skipping hash verification for signature operation "
1145 << next_operation_num_ + 1;
1146 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001147 if (install_plan_->hash_checks_mandatory) {
1148 LOG(ERROR) << "Missing mandatory operation hash for operation "
1149 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001150 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001151 }
1152
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001153 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1154 << " as there's no operation hash in manifest";
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001155 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001156 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001157 }
1158
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001159 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001160 expected_op_hash.assign(operation.data_sha256_hash().data(),
1161 (operation.data_sha256_hash().data() +
1162 operation.data_sha256_hash().size()));
1163
1164 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001165 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001166 if (!operation_hasher.Finalize()) {
1167 LOG(ERROR) << "Unable to compute actual hash of operation "
1168 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001169 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001170 }
1171
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001172 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001173 if (calculated_op_hash != expected_op_hash) {
1174 LOG(ERROR) << "Hash verification failed for operation "
1175 << next_operation_num_ << ". Expected hash = ";
1176 utils::HexDumpVector(expected_op_hash);
1177 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1178 << " bytes at offset: " << operation.data_offset() << " = ";
1179 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001180 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001181 }
1182
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001183 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001184}
1185
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001186#define TEST_AND_RETURN_VAL(_retval, _condition) \
1187 do { \
1188 if (!(_condition)) { \
1189 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1190 return _retval; \
1191 } \
1192 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001193
David Zeuthena99981f2013-04-29 13:42:47 -07001194ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001195 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001196 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001197
1198 // See if we should use the public RSA key in the Omaha response.
1199 base::FilePath path_to_public_key(public_key_path_);
1200 base::FilePath tmp_key;
1201 if (GetPublicKeyFromResponse(&tmp_key))
1202 path_to_public_key = tmp_key;
1203 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1204 if (tmp_key.empty())
1205 tmp_key_remover.set_should_remove(false);
1206
1207 LOG(INFO) << "Verifying payload using public key: "
1208 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001209
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001210 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001211 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001212 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001213 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001214
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001215 // Verifies the payload hash.
1216 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001217 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001218 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001219 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001220 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001221
Darin Petkov437adc42010-10-07 13:12:24 -07001222 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001223 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001224 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001225 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001226 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001227 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001228 !signatures_message_data_.empty());
Darin Petkov437adc42010-10-07 13:12:24 -07001229 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001230 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001231 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001232 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001233 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001234 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymob552a682015-09-30 09:36:49 -07001235 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
1236 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001237 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001238 !hash_data.empty());
Alex Deymob552a682015-09-30 09:36:49 -07001239
1240 if (!PayloadVerifier::VerifySignature(
1241 signatures_message_data_, path_to_public_key.value(), hash_data)) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001242 // The autoupdate_CatchBadSignatures test checks for this string
1243 // in log-files. Keep in sync.
Alex Deymob552a682015-09-30 09:36:49 -07001244 LOG(ERROR) << "Public key verification failed, thus update failed.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001245 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001246 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001247
David Zeuthene7f89172013-10-31 10:21:04 -07001248 LOG(INFO) << "Payload hash matches value in payload.";
1249
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001250 // At this point, we are guaranteed to have downloaded a full payload, i.e
1251 // the one whose size matches the size mentioned in Omaha response. If any
1252 // errors happen after this, it's likely a problem with the payload itself or
1253 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001254 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001255 system_state_->payload_state()->DownloadComplete();
1256
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001257 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001258}
1259
Darin Petkov3aefa862010-12-07 14:45:00 -08001260bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001261 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001262 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001263 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001264 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1265 manifest_.has_new_kernel_info() &&
1266 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001267 *kernel_size = manifest_.new_kernel_info().size();
1268 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001269 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1270 manifest_.new_kernel_info().hash().end());
1271 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1272 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001273 kernel_hash->swap(new_kernel_hash);
1274 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001275 return true;
1276}
1277
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001278namespace {
1279void LogVerifyError(bool is_kern,
1280 const string& local_hash,
1281 const string& expected_hash) {
1282 const char* type = is_kern ? "kernel" : "rootfs";
1283 LOG(ERROR) << "This is a server-side error due to "
1284 << "mismatched delta update image!";
1285 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1286 << "update that must be applied over a " << type << " with "
1287 << "a specific checksum, but the " << type << " we're starting "
1288 << "with doesn't have that checksum! This means that "
1289 << "the delta I've been given doesn't match my existing "
1290 << "system. The " << type << " partition I have has hash: "
1291 << local_hash << " but the update expected me to have "
1292 << expected_hash << " .";
1293 if (is_kern) {
1294 LOG(INFO) << "To get the checksum of a kernel partition on a "
1295 << "booted machine, run this command (change /dev/sda2 "
1296 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1297 << "openssl dgst -sha256 -binary | openssl base64";
1298 } else {
1299 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1300 << "booted machine, run this command (change /dev/sda3 "
1301 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1302 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1303 << "| sed 's/[^0-9]*//') / 256 )) | "
1304 << "openssl dgst -sha256 -binary | openssl base64";
1305 }
1306 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1307 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1308}
1309
1310string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001311 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001312}
1313} // namespace
1314
Darin Petkov698d0412010-10-13 10:59:44 -07001315bool DeltaPerformer::VerifySourcePartitions() {
1316 LOG(INFO) << "Verifying source partitions.";
1317 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001318 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001319 if (manifest_.has_old_kernel_info()) {
1320 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001321 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001322 !install_plan_->source_kernel_hash.empty() &&
1323 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1324 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001325 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001326 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001327 if (!valid) {
1328 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001329 StringForHashBytes(
1330 install_plan_->source_kernel_hash.data(),
1331 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001332 StringForHashBytes(info.hash().data(),
1333 info.hash().size()));
1334 }
1335 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001336 }
1337 if (manifest_.has_old_rootfs_info()) {
1338 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001339 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001340 !install_plan_->source_rootfs_hash.empty() &&
1341 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1342 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001343 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001344 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001345 if (!valid) {
1346 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001347 StringForHashBytes(
1348 install_plan_->source_rootfs_hash.data(),
1349 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001350 StringForHashBytes(info.hash().data(),
1351 info.hash().size()));
1352 }
1353 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001354 }
1355 return true;
1356}
1357
Gilad Arnolddaa27402014-01-23 11:56:17 -08001358void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001359 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001360 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001361 buffer_offset_ += buffer_.size();
1362
1363 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001364 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001365
1366 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001367 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001368}
1369
Darin Petkov0406e402010-10-06 21:33:11 -07001370bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1371 string update_check_response_hash) {
1372 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001373 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1374 next_operation != kUpdateStateOperationInvalid &&
1375 next_operation > 0))
1376 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001377
1378 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001379 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1380 !interrupted_hash.empty() &&
1381 interrupted_hash == update_check_response_hash))
1382 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001383
Darin Petkov61426142010-10-08 11:04:55 -07001384 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001385 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1386 && resumed_update_failures > kMaxResumedUpdateFailures))
1387 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001388
Darin Petkov0406e402010-10-06 21:33:11 -07001389 // Sanity check the rest.
1390 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001391 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1392 next_data_offset >= 0))
1393 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001394
Darin Petkov437adc42010-10-07 13:12:24 -07001395 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001396 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1397 !sha256_context.empty()))
1398 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001399
1400 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001401 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1402 manifest_metadata_size > 0))
1403 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001404
1405 return true;
1406}
1407
Darin Petkov9b230572010-10-08 10:20:09 -07001408bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001409 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1410 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001411 if (!quick) {
1412 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1413 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001414 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001415 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1416 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001417 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001418 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001419 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001420 }
Darin Petkov73058b42010-10-06 16:32:19 -07001421 return true;
1422}
1423
1424bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001425 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001426 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001427 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001428 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001429 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001430 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001431 hash_calculator_.GetContext()));
1432 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1433 buffer_offset_));
1434 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001435
1436 if (next_operation_num_ < num_total_operations_) {
1437 const bool is_kernel_partition =
1438 next_operation_num_ >= num_rootfs_operations_;
Alex Deymoa12ee112015-08-12 22:19:32 -07001439 const InstallOperation& op =
1440 is_kernel_partition
1441 ? manifest_.kernel_install_operations(next_operation_num_ -
1442 num_rootfs_operations_)
1443 : manifest_.install_operations(next_operation_num_);
David Zeuthen41996ad2013-09-24 15:43:24 -07001444 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1445 op.data_length()));
1446 } else {
1447 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1448 0));
1449 }
Darin Petkov0406e402010-10-06 21:33:11 -07001450 }
Darin Petkov73058b42010-10-06 16:32:19 -07001451 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1452 next_operation_num_));
1453 return true;
1454}
1455
Darin Petkov9b230572010-10-08 10:20:09 -07001456bool DeltaPerformer::PrimeUpdateState() {
1457 CHECK(manifest_valid_);
1458 block_size_ = manifest_.block_size();
1459
1460 int64_t next_operation = kUpdateStateOperationInvalid;
1461 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1462 next_operation == kUpdateStateOperationInvalid ||
1463 next_operation <= 0) {
1464 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001465 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001466 return true;
1467 }
1468 next_operation_num_ = next_operation;
1469
1470 // Resuming an update -- load the rest of the update state.
1471 int64_t next_data_offset = -1;
1472 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1473 &next_data_offset) &&
1474 next_data_offset >= 0);
1475 buffer_offset_ = next_data_offset;
1476
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001477 // The signed hash context and the signature blob may be empty if the
1478 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001479 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1480 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001481 string signature_blob;
1482 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1483 signatures_message_data_.assign(signature_blob.begin(),
1484 signature_blob.end());
1485 }
Darin Petkov9b230572010-10-08 10:20:09 -07001486
1487 string hash_context;
1488 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1489 &hash_context) &&
1490 hash_calculator_.SetContext(hash_context));
1491
1492 int64_t manifest_metadata_size = 0;
1493 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1494 &manifest_metadata_size) &&
1495 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001496 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001497
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001498 // Advance the download progress to reflect what doesn't need to be
1499 // re-downloaded.
1500 total_bytes_received_ += buffer_offset_;
1501
Darin Petkov61426142010-10-08 11:04:55 -07001502 // Speculatively count the resume as a failure.
1503 int64_t resumed_update_failures;
1504 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1505 resumed_update_failures++;
1506 } else {
1507 resumed_update_failures = 1;
1508 }
1509 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001510 return true;
1511}
1512
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001513} // namespace chromeos_update_engine