blob: 6094c5a892b2591771909fab2740eeb53b03a71d [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>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070033#include <google/protobuf/repeated_field.h>
34
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070035#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070036#include "update_engine/constants.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070037#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070038#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080039#if USE_MTD
40#include "update_engine/mtd_file_descriptor.h"
41#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070042#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080043#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070044#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070045#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070046#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070047#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070048#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070049
Alex Deymo161c4a12014-05-16 15:56:21 -070050using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070051using std::min;
52using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070053using std::unique_ptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070054using 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 Garrettb8dd1d92013-11-22 17:40:02 -080062const uint64_t DeltaPerformer::kFullPayloadMinorVersion = 0;
Don Garrett4d039442013-10-28 18:40:06 -070063
Darin Petkovabc7bc02011-02-23 14:39:43 -080064const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
65 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080066const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
67const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
68const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
69const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080070
Sen Jiang46e9b172015-08-31 14:11:01 -070071const uint64_t kChromeOSMajorPayloadVersion = 1;
72const uint64_t kBrilloMajorPayloadVersion = 2;
Allie Woodfdf00512015-03-02 13:34:55 -080073const uint32_t kInPlaceMinorPayloadVersion = 1;
74const uint32_t kSourceMinorPayloadVersion = 2;
75
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070076namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070077const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070078const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080079#if USE_MTD
80const int kUbiVolumeAttachTimeout = 5 * 60;
81#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080082
83FileDescriptorPtr CreateFileDescriptor(const char* path) {
84 FileDescriptorPtr ret;
85#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080086 if (strstr(path, "/dev/ubi") == path) {
87 if (!UbiFileDescriptor::IsUbi(path)) {
88 // The volume might not have been attached at boot time.
89 int volume_no;
90 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
91 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
92 }
93 }
94 if (UbiFileDescriptor::IsUbi(path)) {
95 LOG(INFO) << path << " is a UBI device.";
96 ret.reset(new UbiFileDescriptor);
97 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080098 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080099 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800100 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800101 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800102 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800103#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800104 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800105#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700106 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800107#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800108 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700109}
110
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800111// Opens path for read/write. On success returns an open FileDescriptor
112// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
113FileDescriptorPtr OpenFile(const char* path, int* err) {
114 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800115 int mode = O_RDWR;
116#if USE_MTD
117 // On NAND devices, we can either read, or write, but not both. So here we
118 // use O_WRONLY.
119 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
120 mode = O_WRONLY;
121 }
122#endif
123 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800124 *err = errno;
125 PLOG(ERROR) << "Unable to open file " << path;
126 return nullptr;
127 }
128 *err = 0;
129 return fd;
130}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700131} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700132
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800133
134// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
135// arithmetic.
136static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
137 return part * norm / total;
138}
139
140void DeltaPerformer::LogProgress(const char* message_prefix) {
141 // Format operations total count and percentage.
142 string total_operations_str("?");
143 string completed_percentage_str("");
144 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700145 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800146 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
147 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700148 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700149 IntRatio(next_operation_num_, num_total_operations_,
150 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800151 }
152
153 // Format download total count and percentage.
154 size_t payload_size = install_plan_->payload_size;
155 string payload_size_str("?");
156 string downloaded_percentage_str("");
157 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700158 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800159 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
160 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700161 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700162 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800163 }
164
165 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
166 << "/" << total_operations_str << " operations"
167 << completed_percentage_str << ", " << total_bytes_received_
168 << "/" << payload_size_str << " bytes downloaded"
169 << downloaded_percentage_str << ", overall progress "
170 << overall_progress_ << "%";
171}
172
173void DeltaPerformer::UpdateOverallProgress(bool force_log,
174 const char* message_prefix) {
175 // Compute our download and overall progress.
176 unsigned new_overall_progress = 0;
177 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
178 progress_weight_dont_add_up);
179 // Only consider download progress if its total size is known; otherwise
180 // adjust the operations weight to compensate for the absence of download
181 // progress. Also, make sure to cap the download portion at
182 // kProgressDownloadWeight, in case we end up downloading more than we
183 // initially expected (this indicates a problem, but could generally happen).
184 // TODO(garnold) the correction of operations weight when we do not have the
185 // total payload size, as well as the conditional guard below, should both be
186 // eliminated once we ensure that the payload_size in the install plan is
187 // always given and is non-zero. This currently isn't the case during unit
188 // tests (see chromium-os:37969).
189 size_t payload_size = install_plan_->payload_size;
190 unsigned actual_operations_weight = kProgressOperationsWeight;
191 if (payload_size)
192 new_overall_progress += min(
193 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
194 kProgressDownloadWeight)),
195 kProgressDownloadWeight);
196 else
197 actual_operations_weight += kProgressDownloadWeight;
198
199 // Only add completed operations if their total number is known; we definitely
200 // expect an update to have at least one operation, so the expectation is that
201 // this will eventually reach |actual_operations_weight|.
202 if (num_total_operations_)
203 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
204 actual_operations_weight);
205
206 // Progress ratio cannot recede, unless our assumptions about the total
207 // payload size, total number of operations, or the monotonicity of progress
208 // is breached.
209 if (new_overall_progress < overall_progress_) {
210 LOG(WARNING) << "progress counter receded from " << overall_progress_
211 << "% down to " << new_overall_progress << "%; this is a bug";
212 force_log = true;
213 }
214 overall_progress_ = new_overall_progress;
215
216 // Update chunk index, log as needed: if forced by called, or we completed a
217 // progress chunk, or a timeout has expired.
218 base::Time curr_time = base::Time::Now();
219 unsigned curr_progress_chunk =
220 overall_progress_ * kProgressLogMaxChunks / 100;
221 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
222 curr_time > forced_progress_log_time_) {
223 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
224 LogProgress(message_prefix);
225 }
226 last_progress_chunk_ = curr_progress_chunk;
227}
228
229
Gilad Arnoldfe133932014-01-14 12:25:50 -0800230size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
231 size_t max) {
232 const size_t count = *count_p;
233 if (!count)
234 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700235 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800236 const char* bytes_start = *bytes_p;
237 const char* bytes_end = bytes_start + read_len;
238 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
239 *bytes_p = bytes_end;
240 *count_p = count - read_len;
241 return read_len;
242}
243
244
245bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
246 ErrorCode* error) {
247 if (op_result)
248 return true;
249
250 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
251 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700252 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800253 return false;
254}
255
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700256int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700257 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800258 fd_ = OpenFile(path, &err);
259 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700260 path_ = path;
261 return -err;
262}
263
264bool DeltaPerformer::OpenKernel(const char* kernel_path) {
265 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800266 kernel_fd_ = OpenFile(kernel_path, &err);
267 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700268 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800269 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700270}
271
Alex Deymo1beda782015-06-07 23:01:25 +0200272bool DeltaPerformer::OpenSourceRootfs(const string& source_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800273 int err;
274 source_fd_ = OpenFile(source_path.c_str(), &err);
275 return static_cast<bool>(source_fd_);
276}
277
Alex Deymo1beda782015-06-07 23:01:25 +0200278bool DeltaPerformer::OpenSourceKernel(const string& source_kernel_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800279 int err;
280 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
281 return static_cast<bool>(source_kernel_fd_);
282}
283
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700284int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700285 int err = 0;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800286 if (!kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700287 err = errno;
288 PLOG(ERROR) << "Unable to close kernel fd:";
289 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800290 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700291 err = errno;
292 PLOG(ERROR) << "Unable to close rootfs fd:";
293 }
Allie Woodfdf00512015-03-02 13:34:55 -0800294 if (source_fd_ && !source_fd_->Close()) {
295 err = errno;
296 PLOG(ERROR) << "Unable to close source rootfs fd:";
297 }
298 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
299 err = errno;
300 PLOG(ERROR) << "Unable to close source kernel fd:";
301 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700302 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800303 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800304 kernel_fd_.reset();
305 source_fd_.reset();
306 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700307 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800308 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700309 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
310 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800311 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800312 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700313 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700314}
315
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700316namespace {
317
318void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800319 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800320 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
321 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700322}
323
324void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
325 if (manifest.has_old_kernel_info())
326 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
327 if (manifest.has_old_rootfs_info())
328 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
329 if (manifest.has_new_kernel_info())
330 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
331 if (manifest.has_new_rootfs_info())
332 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
333}
334
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700335} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700336
Don Garrett4d039442013-10-28 18:40:06 -0700337uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800338 // Manifest size is stored right after the magic string and the version.
339 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700340}
341
Jay Srinivasanf4318702012-09-24 11:56:24 -0700342uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800343 // Manifest size is stored right after the magic string and the version.
344 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700345}
346
347uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800348 // Actual manifest begins right after the manifest size field.
349 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700350}
351
Gilad Arnoldfe133932014-01-14 12:25:50 -0800352uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800353 return metadata_size_;
354}
355
Allie Woodfdf00512015-03-02 13:34:55 -0800356uint32_t DeltaPerformer::GetMinorVersion() const {
357 if (manifest_.has_minor_version()) {
358 return manifest_.minor_version();
359 } else {
360 return (install_plan_->is_full_update ?
361 kFullPayloadMinorVersion :
362 kSupportedMinorPayloadVersion);
363 }
364}
365
Gilad Arnolddaa27402014-01-23 11:56:17 -0800366bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
367 if (!manifest_parsed_)
368 return false;
369 *out_manifest_p = manifest_;
370 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800371}
372
Jay Srinivasanf4318702012-09-24 11:56:24 -0700373
Darin Petkov9574f7e2011-01-13 10:48:12 -0800374DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800375 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700376 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700377 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800378 uint64_t manifest_size = (metadata_size_ ?
379 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700380
Gilad Arnoldfe133932014-01-14 12:25:50 -0800381 if (!manifest_size) {
382 // Ensure we have data to cover the payload header.
383 if (payload.size() < manifest_offset)
384 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700385
Gilad Arnoldfe133932014-01-14 12:25:50 -0800386 // Validate the magic string.
387 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
388 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700389 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800390 return kMetadataParseError;
391 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800392
393 // Extract the payload version from the metadata.
394 uint64_t major_payload_version;
395 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
396 major_payload_version_size_mismatch);
397 memcpy(&major_payload_version,
398 &payload[GetVersionOffset()],
399 kDeltaVersionSize);
400 // switch big endian to host
401 major_payload_version = be64toh(major_payload_version);
402
403 if (major_payload_version != kSupportedMajorPayloadVersion) {
404 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
405 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700406 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800407 return kMetadataParseError;
408 }
409
410 // Next, parse the manifest size.
411 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
412 manifest_size_size_mismatch);
413 memcpy(&manifest_size,
414 &payload[GetManifestSizeOffset()],
415 kDeltaManifestSizeSize);
416 manifest_size = be64toh(manifest_size); // switch big endian to host
417
418 // If the metadata size is present in install plan, check for it immediately
419 // even before waiting for that many number of bytes to be downloaded in the
420 // payload. This will prevent any attack which relies on us downloading data
421 // beyond the expected metadata size.
422 metadata_size_ = manifest_offset + manifest_size;
423 if (install_plan_->hash_checks_mandatory) {
424 if (install_plan_->metadata_size != metadata_size_) {
425 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
426 << install_plan_->metadata_size
427 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700428 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800429 return kMetadataParseError;
430 }
431 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700432 }
433
434 // Now that we have validated the metadata size, we should wait for the full
435 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800436 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800437 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700438
439 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700440 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700441 // that we just log once (instead of logging n times) if it takes n
442 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800443 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700444 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800445 } else {
446 // For mandatory-cases, we'd have already returned a kMetadataParseError
447 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
448 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
449 << install_plan_->metadata_size
450 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800451 << "Trusting metadata size in payload = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700452 SendUmaStat(ErrorCode::kDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800453 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700454
Jay Srinivasanf4318702012-09-24 11:56:24 -0700455 // We have the full metadata in |payload|. Verify its integrity
456 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800457 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700458 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800459 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800460 // The autoupdate_CatchBadSignatures test checks for this string
461 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800462 LOG(ERROR) << "Mandatory metadata signature validation failed";
463 return kMetadataParseError;
464 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700465
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800466 // For non-mandatory cases, just send a UMA stat.
467 LOG(WARNING) << "Ignoring metadata signature validation failures";
468 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700469 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700470 }
471
Gilad Arnolddaa27402014-01-23 11:56:17 -0800472 // The payload metadata is deemed valid, it's safe to parse the protobuf.
473 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800474 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700475 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800476 return kMetadataParseError;
477 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800478
479 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800480 return kMetadataParseSuccess;
481}
482
Don Garrette410e0f2011-11-10 15:39:01 -0800483// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800484// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700485// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800486bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700487 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700488
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700489 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800490 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800491
492 // Update the total byte downloaded count and the progress logs.
493 total_bytes_received_ += count;
494 UpdateOverallProgress(false, "Completed ");
495
Gilad Arnoldfe133932014-01-14 12:25:50 -0800496 while (!manifest_valid_) {
497 // Read data up to the needed limit; this is either the payload header size,
498 // or the full metadata size (once it becomes known).
499 const bool do_read_header = !metadata_size_;
500 CopyDataToBuffer(&c_bytes, &count,
501 (do_read_header ? GetManifestOffset() :
502 metadata_size_));
503
Gilad Arnolddaa27402014-01-23 11:56:17 -0800504 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700505 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800506 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800507 if (result == kMetadataParseInsufficientData) {
508 // If we just processed the header, make an attempt on the manifest.
509 if (do_read_header && metadata_size_)
510 continue;
511
Don Garrette410e0f2011-11-10 15:39:01 -0800512 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800513 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700514
515 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700516 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700517 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800518 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700519
Gilad Arnoldfe133932014-01-14 12:25:50 -0800520 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800521 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700522 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800523 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700524 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700525
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700526 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700527 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700528 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700529 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800530 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700531 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800532
Allie Woodfdf00512015-03-02 13:34:55 -0800533 // Open source fds if we have a delta payload with minor version 2.
534 if (!install_plan_->is_full_update &&
535 GetMinorVersion() == kSourceMinorPayloadVersion) {
536 if (!OpenSourceRootfs(install_plan_->source_path)) {
537 LOG(ERROR) << "Unable to open source rootfs partition file "
538 << install_plan_->source_path;
539 Close();
540 return false;
541 }
542 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
543 LOG(ERROR) << "Unable to open source kernel partition file "
544 << install_plan_->kernel_source_path;
545 Close();
546 return false;
547 }
548 }
549
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800550 num_rootfs_operations_ = manifest_.install_operations_size();
551 num_total_operations_ =
552 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
553 if (next_operation_num_ > 0)
554 UpdateOverallProgress(true, "Resuming after ");
555 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700556 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800557
558 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700559 // Check if we should cancel the current attempt for any reason.
560 // In this case, *error will have already been populated with the reason
561 // why we're cancelling.
562 if (system_state_->update_attempter()->ShouldCancel(error))
563 return false;
564
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800565 const bool is_kernel_partition =
566 (next_operation_num_ >= num_rootfs_operations_);
Alex Deymoa12ee112015-08-12 22:19:32 -0700567 const InstallOperation& op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800568 is_kernel_partition ?
Alex Deymoa12ee112015-08-12 22:19:32 -0700569 manifest_.kernel_install_operations(next_operation_num_ -
570 num_rootfs_operations_) :
571 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800572
573 CopyDataToBuffer(&c_bytes, &count, op.data_length());
574
575 // Check whether we received all of the next operation's data payload.
576 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700577 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700578
Jay Srinivasanf4318702012-09-24 11:56:24 -0700579 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700580 // Otherwise, keep the old behavior. This serves as a knob to disable
581 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800582 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
583 // we would have already failed in ParsePayloadMetadata method and thus not
584 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700585 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700586 // Note: Validate must be called only if CanPerformInstallOperation is
587 // called. Otherwise, we might be failing operations before even if there
588 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800589 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700590 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800591 if (install_plan_->hash_checks_mandatory) {
592 LOG(ERROR) << "Mandatory operation hash check failed";
593 return false;
594 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700595
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800596 // For non-mandatory cases, just send a UMA stat.
597 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700598 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700599 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700600 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700601 }
602
Darin Petkov45580e42010-10-08 14:02:40 -0700603 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700604 ScopedTerminatorExitUnblocker exit_unblocker =
605 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800606
607 bool op_result;
Alex Deymoa12ee112015-08-12 22:19:32 -0700608 if (op.type() == InstallOperation::REPLACE ||
609 op.type() == InstallOperation::REPLACE_BZ)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800610 op_result = HandleOpResult(
611 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700612 else if (op.type() == InstallOperation::MOVE)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800613 op_result = HandleOpResult(
614 PerformMoveOperation(op, is_kernel_partition), "move", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700615 else if (op.type() == InstallOperation::BSDIFF)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800616 op_result = HandleOpResult(
617 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700618 else if (op.type() == InstallOperation::SOURCE_COPY)
Allie Wood9f6f0a52015-03-30 11:25:47 -0700619 op_result =
620 HandleOpResult(PerformSourceCopyOperation(op, is_kernel_partition),
621 "source_copy", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700622 else if (op.type() == InstallOperation::SOURCE_BSDIFF)
Allie Wood9f6f0a52015-03-30 11:25:47 -0700623 op_result =
624 HandleOpResult(PerformSourceBsdiffOperation(op, is_kernel_partition),
625 "source_bsdiff", error);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800626 else
627 op_result = HandleOpResult(false, "unknown", error);
628
629 if (!op_result)
630 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800631
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700632 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800633 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700634 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700635 }
Don Garrette410e0f2011-11-10 15:39:01 -0800636 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700637}
638
David Zeuthen8f191b22013-08-06 12:27:50 -0700639bool DeltaPerformer::IsManifestValid() {
640 return manifest_valid_;
641}
642
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700643bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700644 const chromeos_update_engine::InstallOperation& operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700645 // Move and source_copy operations don't require any data blob, so they can
646 // always be performed.
Alex Deymoa12ee112015-08-12 22:19:32 -0700647 if (operation.type() == InstallOperation::MOVE ||
648 operation.type() == InstallOperation::SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700649 return true;
650
651 // See if we have the entire data blob in the buffer
652 if (operation.data_offset() < buffer_offset_) {
653 LOG(ERROR) << "we threw away data it seems?";
654 return false;
655 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700656
Gilad Arnoldfe133932014-01-14 12:25:50 -0800657 return (operation.data_offset() + operation.data_length() <=
658 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700659}
660
Alex Deymoa12ee112015-08-12 22:19:32 -0700661bool DeltaPerformer::PerformReplaceOperation(const InstallOperation& operation,
662 bool is_kernel_partition) {
663 CHECK(operation.type() == InstallOperation::REPLACE ||
664 operation.type() == InstallOperation::REPLACE_BZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700665
666 // Since we delete data off the beginning of the buffer as we use it,
667 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700668 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
669 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700670
Darin Petkov437adc42010-10-07 13:12:24 -0700671 // Extract the signature message if it's in this operation.
672 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700673
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700674 DirectExtentWriter direct_writer;
675 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700676 unique_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700677
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700678 // Since bzip decompression is optional, we have a variable writer that will
679 // point to one of the ExtentWriter objects above.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700680 ExtentWriter* writer = nullptr;
Alex Deymoa12ee112015-08-12 22:19:32 -0700681 if (operation.type() == InstallOperation::REPLACE) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700682 writer = &zero_pad_writer;
Alex Deymoa12ee112015-08-12 22:19:32 -0700683 } else if (operation.type() == InstallOperation::REPLACE_BZ) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700684 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
685 writer = bzip_writer.get();
686 } else {
687 NOTREACHED();
688 }
689
690 // Create a vector of extents to pass to the ExtentWriter.
691 vector<Extent> extents;
692 for (int i = 0; i < operation.dst_extents_size(); i++) {
693 extents.push_back(operation.dst_extents(i));
694 }
695
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800696 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700697
698 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800699 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700700 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700701
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700702 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800703 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700704 return true;
705}
706
Alex Deymoa12ee112015-08-12 22:19:32 -0700707bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation,
708 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700709 // Calculate buffer size. Note, this function doesn't do a sliding
710 // window to copy in case the source and destination blocks overlap.
711 // If we wanted to do a sliding window, we could program the server
712 // to generate deltas that effectively did a sliding window.
713
714 uint64_t blocks_to_read = 0;
715 for (int i = 0; i < operation.src_extents_size(); i++)
716 blocks_to_read += operation.src_extents(i).num_blocks();
717
718 uint64_t blocks_to_write = 0;
719 for (int i = 0; i < operation.dst_extents_size(); i++)
720 blocks_to_write += operation.dst_extents(i).num_blocks();
721
722 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800723 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700724
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800725 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700726
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700727 // Read in bytes.
728 ssize_t bytes_read = 0;
729 for (int i = 0; i < operation.src_extents_size(); i++) {
730 ssize_t bytes_read_this_iteration = 0;
731 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200732 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700733 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
734 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
735 &buf[bytes_read],
736 bytes,
737 extent.start_block() * block_size_,
738 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700739 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200740 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700741 bytes_read += bytes_read_this_iteration;
742 }
743
744 // Write bytes out.
745 ssize_t bytes_written = 0;
746 for (int i = 0; i < operation.dst_extents_size(); i++) {
747 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200748 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700749 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
750 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
751 &buf[bytes_written],
752 bytes,
753 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200754 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700755 }
756 DCHECK_EQ(bytes_written, bytes_read);
757 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
758 return true;
759}
760
Allie Wood9f6f0a52015-03-30 11:25:47 -0700761namespace {
762
763// Takes |extents| and fills an empty vector |blocks| with a block index for
764// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
765void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
766 vector<uint64_t>* blocks) {
767 for (Extent ext : extents) {
768 for (uint64_t j = 0; j < ext.num_blocks(); j++)
769 blocks->push_back(ext.start_block() + j);
770 }
771}
772
773// Takes |extents| and returns the number of blocks in those extents.
774uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
775 uint64_t sum = 0;
776 for (Extent ext : extents) {
777 sum += ext.num_blocks();
778 }
779 return sum;
780}
781
782} // namespace
783
784bool DeltaPerformer::PerformSourceCopyOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700785 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700786 bool is_kernel_partition) {
787 if (operation.has_src_length())
788 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
789 if (operation.has_dst_length())
790 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
791
792 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
793 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
794 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
795
796 // Create vectors of all the individual src/dst blocks.
797 vector<uint64_t> src_blocks;
798 vector<uint64_t> dst_blocks;
799 ExtentsToBlocks(operation.src_extents(), &src_blocks);
800 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
801 DCHECK_EQ(src_blocks.size(), blocks_to_read);
802 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
803
804 FileDescriptorPtr src_fd =
805 is_kernel_partition ? source_kernel_fd_ : source_fd_;
806 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
807
808 chromeos::Blob buf(block_size_);
809 ssize_t bytes_read = 0;
810 // Read/write one block at a time.
811 for (uint64_t i = 0; i < blocks_to_read; i++) {
812 ssize_t bytes_read_this_iteration = 0;
813 uint64_t src_block = src_blocks[i];
814 uint64_t dst_block = dst_blocks[i];
815
816 // Read in bytes.
817 TEST_AND_RETURN_FALSE(
818 utils::PReadAll(src_fd,
819 buf.data(),
820 block_size_,
821 src_block * block_size_,
822 &bytes_read_this_iteration));
823
824 // Write bytes out.
825 TEST_AND_RETURN_FALSE(
826 utils::PWriteAll(dst_fd,
827 buf.data(),
828 block_size_,
829 dst_block * block_size_));
830
831 bytes_read += bytes_read_this_iteration;
832 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
833 static_cast<ssize_t>(block_size_));
834 }
835 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
836 return true;
837}
838
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700839bool DeltaPerformer::ExtentsToBsdiffPositionsString(
840 const RepeatedPtrField<Extent>& extents,
841 uint64_t block_size,
842 uint64_t full_length,
843 string* positions_string) {
844 string ret;
845 uint64_t length = 0;
846 for (int i = 0; i < extents.size(); i++) {
847 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700848 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700849 uint64_t this_length = min(full_length - length,
850 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700851 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700852 length += this_length;
853 }
854 TEST_AND_RETURN_FALSE(length == full_length);
855 if (!ret.empty())
856 ret.resize(ret.size() - 1); // Strip trailing comma off
857 *positions_string = ret;
858 return true;
859}
860
Alex Deymoa12ee112015-08-12 22:19:32 -0700861bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation,
862 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700863 // Since we delete data off the beginning of the buffer as we use it,
864 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700865 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
866 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700867
868 string input_positions;
869 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
870 block_size_,
871 operation.src_length(),
872 &input_positions));
873 string output_positions;
874 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
875 block_size_,
876 operation.dst_length(),
877 &output_positions));
878
879 string temp_filename;
880 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
881 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700882 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700883 ScopedPathUnlinker path_unlinker(temp_filename);
884 {
885 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
886 ScopedFdCloser fd_closer(&fd);
887 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800888 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700889 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700890
Darin Petkov7f2ec752013-04-03 14:45:19 +0200891 // Update the buffer to release the patch data memory as soon as the patch
892 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800893 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200894
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800895 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700896 vector<string> cmd{kBspatchPath, path, path, temp_filename,
897 input_positions, output_positions};
898
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700899 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700900 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700901 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
902 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700903 TEST_AND_RETURN_FALSE(return_code == 0);
904
905 if (operation.dst_length() % block_size_) {
906 // Zero out rest of final block.
907 // TODO(adlr): build this into bspatch; it's more efficient that way.
908 const Extent& last_extent =
909 operation.dst_extents(operation.dst_extents_size() - 1);
910 const uint64_t end_byte =
911 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
912 const uint64_t begin_byte =
913 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800914 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800915 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700916 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800917 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700918 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700919 return true;
920}
921
Allie Wood9f6f0a52015-03-30 11:25:47 -0700922bool DeltaPerformer::PerformSourceBsdiffOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700923 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700924 bool is_kernel_partition) {
925 // Since we delete data off the beginning of the buffer as we use it,
926 // the data we need should be exactly at the beginning of the buffer.
927 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
928 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
929 if (operation.has_src_length())
930 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
931 if (operation.has_dst_length())
932 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
933
934 string input_positions;
935 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
936 block_size_,
937 operation.src_length(),
938 &input_positions));
939 string output_positions;
940 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
941 block_size_,
942 operation.dst_length(),
943 &output_positions));
944
945 string temp_filename;
946 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
947 &temp_filename,
948 nullptr));
949 ScopedPathUnlinker path_unlinker(temp_filename);
950 {
951 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
952 ScopedFdCloser fd_closer(&fd);
953 TEST_AND_RETURN_FALSE(
954 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
955 }
956
957 // Update the buffer to release the patch data memory as soon as the patch
958 // file is written out.
959 DiscardBuffer(true);
960
961 const string& src_path = is_kernel_partition ?
962 install_plan_->kernel_source_path :
963 install_plan_->source_path;
964 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
965 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
966 input_positions, output_positions};
967
968 int return_code = 0;
969 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700970 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
971 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -0700972 TEST_AND_RETURN_FALSE(return_code == 0);
973 return true;
974}
975
Darin Petkovd7061ab2010-10-06 14:37:09 -0700976bool DeltaPerformer::ExtractSignatureMessage(
Alex Deymoa12ee112015-08-12 22:19:32 -0700977 const InstallOperation& operation) {
978 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -0700979 !manifest_.has_signatures_offset() ||
980 manifest_.signatures_offset() != operation.data_offset()) {
981 return false;
982 }
983 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
984 manifest_.signatures_size() == operation.data_length());
985 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
986 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
987 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700988 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700989 buffer_.begin(),
990 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700991
992 // Save the signature blob because if the update is interrupted after the
993 // download phase we don't go through this path anymore. Some alternatives to
994 // consider:
995 //
996 // 1. On resume, re-download the signature blob from the server and re-verify
997 // it.
998 //
999 // 2. Verify the signature as soon as it's received and don't checkpoint the
1000 // blob and the signed sha-256 context.
1001 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001002 string(signatures_message_data_.begin(),
1003 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001004 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001005 // The hash of all data consumed so far should be verified against the signed
1006 // hash.
1007 signed_hash_context_ = hash_calculator_.GetContext();
1008 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1009 signed_hash_context_))
1010 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001011 LOG(INFO) << "Extracted signature data of size "
1012 << manifest_.signatures_size() << " at "
1013 << manifest_.signatures_offset();
1014 return true;
1015}
1016
David Zeuthene7f89172013-10-31 10:21:04 -07001017bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1018 if (system_state_->hardware()->IsOfficialBuild() ||
1019 utils::FileExists(public_key_path_.c_str()) ||
1020 install_plan_->public_key_rsa.empty())
1021 return false;
1022
1023 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1024 out_tmp_key))
1025 return false;
1026
1027 return true;
1028}
1029
David Zeuthena99981f2013-04-29 13:42:47 -07001030ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001031 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001032
Jay Srinivasanf4318702012-09-24 11:56:24 -07001033 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001034 if (install_plan_->hash_checks_mandatory) {
1035 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001036 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001037 }
1038
1039 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -07001040 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001041 SendUmaStat(ErrorCode::kDownloadMetadataSignatureMissingError);
1042 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001043 }
1044
1045 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001046 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001047 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001048 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001049 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1050 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001051 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001052 }
1053
David Zeuthene7f89172013-10-31 10:21:04 -07001054 // See if we should use the public RSA key in the Omaha response.
1055 base::FilePath path_to_public_key(public_key_path_);
1056 base::FilePath tmp_key;
1057 if (GetPublicKeyFromResponse(&tmp_key))
1058 path_to_public_key = tmp_key;
1059 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1060 if (tmp_key.empty())
1061 tmp_key_remover.set_should_remove(false);
1062
1063 LOG(INFO) << "Verifying metadata hash signature using public key: "
1064 << path_to_public_key.value();
1065
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001066 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001067 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1068 path_to_public_key.value(),
1069 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001070 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001071 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001072 }
1073
Jay Srinivasanf4318702012-09-24 11:56:24 -07001074 OmahaHashCalculator metadata_hasher;
1075 metadata_hasher.Update(metadata, metadata_size);
1076 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001077 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001078 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001079 }
1080
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001081 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001082 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001083 if (calculated_metadata_hash.empty()) {
1084 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001085 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001086 }
1087
Jay Srinivasanf4318702012-09-24 11:56:24 -07001088 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001089 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001090 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001091 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001092 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001093 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001094 }
1095
David Zeuthenbc27aac2013-11-26 11:17:48 -08001096 // The autoupdate_CatchBadSignatures test checks for this string in
1097 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001098 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001099 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001100}
1101
Gilad Arnold21504f02013-05-24 08:51:22 -07001102ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001103 // Perform assorted checks to sanity check the manifest, make sure it
1104 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001105 //
1106 // TODO(garnold) in general, the presence of an old partition hash should be
1107 // the sole indicator for a delta update, as we would generally like update
1108 // payloads to be self contained and not assume an Omaha response to tell us
1109 // that. However, since this requires some massive reengineering of the update
1110 // flow (making filesystem copying happen conditionally only *after*
1111 // downloading and parsing of the update manifest) we'll put it off for now.
1112 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001113 if (install_plan_->is_full_update) {
1114 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1115 LOG(ERROR) << "Purported full payload contains old partition "
1116 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001117 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001118 }
1119
1120 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1121 LOG(ERROR) << "Manifest contains minor version "
1122 << manifest_.minor_version()
1123 << ", but all full payloads should have version "
1124 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001125 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001126 }
1127 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001128 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001129 LOG(ERROR) << "Manifest contains minor version "
1130 << manifest_.minor_version()
1131 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001132 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001133 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001134 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001135 }
1136
1137 // TODO(garnold) we should be adding more and more manifest checks, such as
1138 // partition boundaries etc (see chromium-os:37661).
1139
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001140 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001141}
1142
David Zeuthena99981f2013-04-29 13:42:47 -07001143ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001144 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001145 if (!operation.data_sha256_hash().size()) {
1146 if (!operation.data_length()) {
1147 // Operations that do not have any data blob won't have any operation hash
1148 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001149 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001150 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001151 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001152 }
1153
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001154 // No hash is present for an operation that has data blobs. This shouldn't
1155 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001156 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001157 // hashes. So if it happens it means either we've turned operation hash
1158 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001159 // One caveat though: The last operation is a dummy signature operation
1160 // that doesn't have a hash at the time the manifest is created. So we
1161 // should not complaint about that operation. This operation can be
1162 // recognized by the fact that it's offset is mentioned in the manifest.
1163 if (manifest_.signatures_offset() &&
1164 manifest_.signatures_offset() == operation.data_offset()) {
1165 LOG(INFO) << "Skipping hash verification for signature operation "
1166 << next_operation_num_ + 1;
1167 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001168 if (install_plan_->hash_checks_mandatory) {
1169 LOG(ERROR) << "Missing mandatory operation hash for operation "
1170 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001171 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001172 }
1173
1174 // For non-mandatory cases, just send a UMA stat.
1175 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1176 << " as there's no operation hash in manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001177 SendUmaStat(ErrorCode::kDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001178 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001179 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001180 }
1181
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001182 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001183 expected_op_hash.assign(operation.data_sha256_hash().data(),
1184 (operation.data_sha256_hash().data() +
1185 operation.data_sha256_hash().size()));
1186
1187 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001188 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001189 if (!operation_hasher.Finalize()) {
1190 LOG(ERROR) << "Unable to compute actual hash of operation "
1191 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001192 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001193 }
1194
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001195 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001196 if (calculated_op_hash != expected_op_hash) {
1197 LOG(ERROR) << "Hash verification failed for operation "
1198 << next_operation_num_ << ". Expected hash = ";
1199 utils::HexDumpVector(expected_op_hash);
1200 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1201 << " bytes at offset: " << operation.data_offset() << " = ";
1202 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001203 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001204 }
1205
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001206 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001207}
1208
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001209#define TEST_AND_RETURN_VAL(_retval, _condition) \
1210 do { \
1211 if (!(_condition)) { \
1212 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1213 return _retval; \
1214 } \
1215 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001216
David Zeuthena99981f2013-04-29 13:42:47 -07001217ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001218 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001219 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001220
1221 // See if we should use the public RSA key in the Omaha response.
1222 base::FilePath path_to_public_key(public_key_path_);
1223 base::FilePath tmp_key;
1224 if (GetPublicKeyFromResponse(&tmp_key))
1225 path_to_public_key = tmp_key;
1226 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1227 if (tmp_key.empty())
1228 tmp_key_remover.set_should_remove(false);
1229
1230 LOG(INFO) << "Verifying payload using public key: "
1231 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001232
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001233 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001234 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001235 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001236 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001237
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001238 // Verifies the payload hash.
1239 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001240 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001241 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001242 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001243 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001244
Darin Petkov437adc42010-10-07 13:12:24 -07001245 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001246 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001247 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001248 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001249 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001251 !signatures_message_data_.empty());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001252 chromeos::Blob signed_hash_data;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001253 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Alex Deymo923d8fa2014-07-15 17:58:51 -07001254 PayloadVerifier::VerifySignature(
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001255 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001256 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001257 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001258 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001259 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001260 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001261 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001262 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001263 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001264 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001265 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001266 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001267 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001268 // The autoupdate_CatchBadSignatures test checks for this string
1269 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001270 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001271 "Attached Signature:";
1272 utils::HexDumpVector(signed_hash_data);
1273 LOG(ERROR) << "Computed Signature:";
1274 utils::HexDumpVector(hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001275 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001276 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001277
David Zeuthene7f89172013-10-31 10:21:04 -07001278 LOG(INFO) << "Payload hash matches value in payload.";
1279
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001280 // At this point, we are guaranteed to have downloaded a full payload, i.e
1281 // the one whose size matches the size mentioned in Omaha response. If any
1282 // errors happen after this, it's likely a problem with the payload itself or
1283 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001284 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001285 system_state_->payload_state()->DownloadComplete();
1286
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001287 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001288}
1289
Darin Petkov3aefa862010-12-07 14:45:00 -08001290bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001291 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001292 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001293 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001294 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1295 manifest_.has_new_kernel_info() &&
1296 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001297 *kernel_size = manifest_.new_kernel_info().size();
1298 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001299 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1300 manifest_.new_kernel_info().hash().end());
1301 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1302 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001303 kernel_hash->swap(new_kernel_hash);
1304 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001305 return true;
1306}
1307
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001308namespace {
1309void LogVerifyError(bool is_kern,
1310 const string& local_hash,
1311 const string& expected_hash) {
1312 const char* type = is_kern ? "kernel" : "rootfs";
1313 LOG(ERROR) << "This is a server-side error due to "
1314 << "mismatched delta update image!";
1315 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1316 << "update that must be applied over a " << type << " with "
1317 << "a specific checksum, but the " << type << " we're starting "
1318 << "with doesn't have that checksum! This means that "
1319 << "the delta I've been given doesn't match my existing "
1320 << "system. The " << type << " partition I have has hash: "
1321 << local_hash << " but the update expected me to have "
1322 << expected_hash << " .";
1323 if (is_kern) {
1324 LOG(INFO) << "To get the checksum of a kernel partition on a "
1325 << "booted machine, run this command (change /dev/sda2 "
1326 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1327 << "openssl dgst -sha256 -binary | openssl base64";
1328 } else {
1329 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1330 << "booted machine, run this command (change /dev/sda3 "
1331 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1332 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1333 << "| sed 's/[^0-9]*//') / 256 )) | "
1334 << "openssl dgst -sha256 -binary | openssl base64";
1335 }
1336 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1337 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1338}
1339
1340string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001341 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001342}
1343} // namespace
1344
Darin Petkov698d0412010-10-13 10:59:44 -07001345bool DeltaPerformer::VerifySourcePartitions() {
1346 LOG(INFO) << "Verifying source partitions.";
1347 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001348 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001349 if (manifest_.has_old_kernel_info()) {
1350 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001351 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001352 !install_plan_->source_kernel_hash.empty() &&
1353 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1354 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001355 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001356 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001357 if (!valid) {
1358 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001359 StringForHashBytes(
1360 install_plan_->source_kernel_hash.data(),
1361 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001362 StringForHashBytes(info.hash().data(),
1363 info.hash().size()));
1364 }
1365 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001366 }
1367 if (manifest_.has_old_rootfs_info()) {
1368 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001369 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001370 !install_plan_->source_rootfs_hash.empty() &&
1371 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1372 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001373 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001374 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001375 if (!valid) {
1376 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001377 StringForHashBytes(
1378 install_plan_->source_rootfs_hash.data(),
1379 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001380 StringForHashBytes(info.hash().data(),
1381 info.hash().size()));
1382 }
1383 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001384 }
1385 return true;
1386}
1387
Gilad Arnolddaa27402014-01-23 11:56:17 -08001388void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001389 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001390 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001391 buffer_offset_ += buffer_.size();
1392
1393 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001394 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001395
1396 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001397 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001398}
1399
Darin Petkov0406e402010-10-06 21:33:11 -07001400bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1401 string update_check_response_hash) {
1402 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001403 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1404 next_operation != kUpdateStateOperationInvalid &&
1405 next_operation > 0))
1406 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001407
1408 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001409 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1410 !interrupted_hash.empty() &&
1411 interrupted_hash == update_check_response_hash))
1412 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001413
Darin Petkov61426142010-10-08 11:04:55 -07001414 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001415 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1416 && resumed_update_failures > kMaxResumedUpdateFailures))
1417 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001418
Darin Petkov0406e402010-10-06 21:33:11 -07001419 // Sanity check the rest.
1420 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001421 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1422 next_data_offset >= 0))
1423 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001424
Darin Petkov437adc42010-10-07 13:12:24 -07001425 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001426 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1427 !sha256_context.empty()))
1428 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001429
1430 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001431 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1432 manifest_metadata_size > 0))
1433 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001434
1435 return true;
1436}
1437
Darin Petkov9b230572010-10-08 10:20:09 -07001438bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001439 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1440 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001441 if (!quick) {
1442 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1443 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001444 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001445 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1446 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001447 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001448 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001449 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001450 }
Darin Petkov73058b42010-10-06 16:32:19 -07001451 return true;
1452}
1453
1454bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001455 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001456 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001457 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001458 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001459 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001460 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001461 hash_calculator_.GetContext()));
1462 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1463 buffer_offset_));
1464 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001465
1466 if (next_operation_num_ < num_total_operations_) {
1467 const bool is_kernel_partition =
1468 next_operation_num_ >= num_rootfs_operations_;
Alex Deymoa12ee112015-08-12 22:19:32 -07001469 const InstallOperation& op =
1470 is_kernel_partition
1471 ? manifest_.kernel_install_operations(next_operation_num_ -
1472 num_rootfs_operations_)
1473 : manifest_.install_operations(next_operation_num_);
David Zeuthen41996ad2013-09-24 15:43:24 -07001474 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1475 op.data_length()));
1476 } else {
1477 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1478 0));
1479 }
Darin Petkov0406e402010-10-06 21:33:11 -07001480 }
Darin Petkov73058b42010-10-06 16:32:19 -07001481 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1482 next_operation_num_));
1483 return true;
1484}
1485
Darin Petkov9b230572010-10-08 10:20:09 -07001486bool DeltaPerformer::PrimeUpdateState() {
1487 CHECK(manifest_valid_);
1488 block_size_ = manifest_.block_size();
1489
1490 int64_t next_operation = kUpdateStateOperationInvalid;
1491 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1492 next_operation == kUpdateStateOperationInvalid ||
1493 next_operation <= 0) {
1494 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001495 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001496 return true;
1497 }
1498 next_operation_num_ = next_operation;
1499
1500 // Resuming an update -- load the rest of the update state.
1501 int64_t next_data_offset = -1;
1502 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1503 &next_data_offset) &&
1504 next_data_offset >= 0);
1505 buffer_offset_ = next_data_offset;
1506
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001507 // The signed hash context and the signature blob may be empty if the
1508 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001509 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1510 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001511 string signature_blob;
1512 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1513 signatures_message_data_.assign(signature_blob.begin(),
1514 signature_blob.end());
1515 }
Darin Petkov9b230572010-10-08 10:20:09 -07001516
1517 string hash_context;
1518 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1519 &hash_context) &&
1520 hash_calculator_.SetContext(hash_context));
1521
1522 int64_t manifest_metadata_size = 0;
1523 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1524 &manifest_metadata_size) &&
1525 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001526 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001527
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001528 // Advance the download progress to reflect what doesn't need to be
1529 // re-downloaded.
1530 total_bytes_received_ += buffer_offset_;
1531
Darin Petkov61426142010-10-08 11:04:55 -07001532 // Speculatively count the resume as a failure.
1533 int64_t resumed_update_failures;
1534 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1535 resumed_update_failures++;
1536 } else {
1537 resumed_update_failures = 1;
1538 }
1539 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001540 return true;
1541}
1542
David Zeuthena99981f2013-04-29 13:42:47 -07001543void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001544 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001545}
1546
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001547} // namespace chromeos_update_engine