blob: de877b8f4214db9167a77ab028226b54e505ce5d [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
Allie Woodfdf00512015-03-02 13:34:55 -080071const uint32_t kInPlaceMinorPayloadVersion = 1;
72const uint32_t kSourceMinorPayloadVersion = 2;
73
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070074namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070075const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070076const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080077#if USE_MTD
78const int kUbiVolumeAttachTimeout = 5 * 60;
79#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080080
81FileDescriptorPtr CreateFileDescriptor(const char* path) {
82 FileDescriptorPtr ret;
83#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080084 if (strstr(path, "/dev/ubi") == path) {
85 if (!UbiFileDescriptor::IsUbi(path)) {
86 // The volume might not have been attached at boot time.
87 int volume_no;
88 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
89 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
90 }
91 }
92 if (UbiFileDescriptor::IsUbi(path)) {
93 LOG(INFO) << path << " is a UBI device.";
94 ret.reset(new UbiFileDescriptor);
95 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080096 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080097 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080098 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080099 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800100 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800101#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800102 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800103#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700104 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800105#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800106 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700107}
108
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800109// Opens path for read/write. On success returns an open FileDescriptor
110// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
111FileDescriptorPtr OpenFile(const char* path, int* err) {
112 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800113 int mode = O_RDWR;
114#if USE_MTD
115 // On NAND devices, we can either read, or write, but not both. So here we
116 // use O_WRONLY.
117 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
118 mode = O_WRONLY;
119 }
120#endif
121 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800122 *err = errno;
123 PLOG(ERROR) << "Unable to open file " << path;
124 return nullptr;
125 }
126 *err = 0;
127 return fd;
128}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700129} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700130
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800131
132// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
133// arithmetic.
134static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
135 return part * norm / total;
136}
137
138void DeltaPerformer::LogProgress(const char* message_prefix) {
139 // Format operations total count and percentage.
140 string total_operations_str("?");
141 string completed_percentage_str("");
142 if (num_total_operations_) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700143 total_operations_str = std::to_string(num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800144 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
145 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700146 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700147 IntRatio(next_operation_num_, num_total_operations_,
148 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800149 }
150
151 // Format download total count and percentage.
152 size_t payload_size = install_plan_->payload_size;
153 string payload_size_str("?");
154 string downloaded_percentage_str("");
155 if (payload_size) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700156 payload_size_str = std::to_string(payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800157 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
158 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700159 base::StringPrintf(" (%" PRIu64 "%%)",
Alex Deymoc00c98a2015-03-17 17:38:00 -0700160 IntRatio(total_bytes_received_, payload_size, 100));
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800161 }
162
163 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
164 << "/" << total_operations_str << " operations"
165 << completed_percentage_str << ", " << total_bytes_received_
166 << "/" << payload_size_str << " bytes downloaded"
167 << downloaded_percentage_str << ", overall progress "
168 << overall_progress_ << "%";
169}
170
171void DeltaPerformer::UpdateOverallProgress(bool force_log,
172 const char* message_prefix) {
173 // Compute our download and overall progress.
174 unsigned new_overall_progress = 0;
175 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
176 progress_weight_dont_add_up);
177 // Only consider download progress if its total size is known; otherwise
178 // adjust the operations weight to compensate for the absence of download
179 // progress. Also, make sure to cap the download portion at
180 // kProgressDownloadWeight, in case we end up downloading more than we
181 // initially expected (this indicates a problem, but could generally happen).
182 // TODO(garnold) the correction of operations weight when we do not have the
183 // total payload size, as well as the conditional guard below, should both be
184 // eliminated once we ensure that the payload_size in the install plan is
185 // always given and is non-zero. This currently isn't the case during unit
186 // tests (see chromium-os:37969).
187 size_t payload_size = install_plan_->payload_size;
188 unsigned actual_operations_weight = kProgressOperationsWeight;
189 if (payload_size)
190 new_overall_progress += min(
191 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
192 kProgressDownloadWeight)),
193 kProgressDownloadWeight);
194 else
195 actual_operations_weight += kProgressDownloadWeight;
196
197 // Only add completed operations if their total number is known; we definitely
198 // expect an update to have at least one operation, so the expectation is that
199 // this will eventually reach |actual_operations_weight|.
200 if (num_total_operations_)
201 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
202 actual_operations_weight);
203
204 // Progress ratio cannot recede, unless our assumptions about the total
205 // payload size, total number of operations, or the monotonicity of progress
206 // is breached.
207 if (new_overall_progress < overall_progress_) {
208 LOG(WARNING) << "progress counter receded from " << overall_progress_
209 << "% down to " << new_overall_progress << "%; this is a bug";
210 force_log = true;
211 }
212 overall_progress_ = new_overall_progress;
213
214 // Update chunk index, log as needed: if forced by called, or we completed a
215 // progress chunk, or a timeout has expired.
216 base::Time curr_time = base::Time::Now();
217 unsigned curr_progress_chunk =
218 overall_progress_ * kProgressLogMaxChunks / 100;
219 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
220 curr_time > forced_progress_log_time_) {
221 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
222 LogProgress(message_prefix);
223 }
224 last_progress_chunk_ = curr_progress_chunk;
225}
226
227
Gilad Arnoldfe133932014-01-14 12:25:50 -0800228size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
229 size_t max) {
230 const size_t count = *count_p;
231 if (!count)
232 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700233 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800234 const char* bytes_start = *bytes_p;
235 const char* bytes_end = bytes_start + read_len;
236 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
237 *bytes_p = bytes_end;
238 *count_p = count - read_len;
239 return read_len;
240}
241
242
243bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
244 ErrorCode* error) {
245 if (op_result)
246 return true;
247
248 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
249 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700250 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800251 return false;
252}
253
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700254int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700255 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800256 fd_ = OpenFile(path, &err);
257 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700258 path_ = path;
259 return -err;
260}
261
262bool DeltaPerformer::OpenKernel(const char* kernel_path) {
263 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800264 kernel_fd_ = OpenFile(kernel_path, &err);
265 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700266 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800267 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700268}
269
Alex Deymo1beda782015-06-07 23:01:25 +0200270bool DeltaPerformer::OpenSourceRootfs(const string& source_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800271 int err;
272 source_fd_ = OpenFile(source_path.c_str(), &err);
273 return static_cast<bool>(source_fd_);
274}
275
Alex Deymo1beda782015-06-07 23:01:25 +0200276bool DeltaPerformer::OpenSourceKernel(const string& source_kernel_path) {
Allie Woodfdf00512015-03-02 13:34:55 -0800277 int err;
278 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
279 return static_cast<bool>(source_kernel_fd_);
280}
281
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700282int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700283 int err = 0;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800284 if (!kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700285 err = errno;
286 PLOG(ERROR) << "Unable to close kernel fd:";
287 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800288 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700289 err = errno;
290 PLOG(ERROR) << "Unable to close rootfs fd:";
291 }
Allie Woodfdf00512015-03-02 13:34:55 -0800292 if (source_fd_ && !source_fd_->Close()) {
293 err = errno;
294 PLOG(ERROR) << "Unable to close source rootfs fd:";
295 }
296 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
297 err = errno;
298 PLOG(ERROR) << "Unable to close source kernel fd:";
299 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700300 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800301 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800302 kernel_fd_.reset();
303 source_fd_.reset();
304 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700305 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800306 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700307 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
308 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800309 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800310 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700311 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700312}
313
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700314namespace {
315
316void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800317 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800318 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
319 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700320}
321
322void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
323 if (manifest.has_old_kernel_info())
324 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
325 if (manifest.has_old_rootfs_info())
326 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
327 if (manifest.has_new_kernel_info())
328 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
329 if (manifest.has_new_rootfs_info())
330 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
331}
332
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700333} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700334
Don Garrett4d039442013-10-28 18:40:06 -0700335uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800336 // Manifest size is stored right after the magic string and the version.
337 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700338}
339
Jay Srinivasanf4318702012-09-24 11:56:24 -0700340uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800341 // Manifest size is stored right after the magic string and the version.
342 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700343}
344
345uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800346 // Actual manifest begins right after the manifest size field.
347 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700348}
349
Gilad Arnoldfe133932014-01-14 12:25:50 -0800350uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800351 return metadata_size_;
352}
353
Allie Woodfdf00512015-03-02 13:34:55 -0800354uint32_t DeltaPerformer::GetMinorVersion() const {
355 if (manifest_.has_minor_version()) {
356 return manifest_.minor_version();
357 } else {
358 return (install_plan_->is_full_update ?
359 kFullPayloadMinorVersion :
360 kSupportedMinorPayloadVersion);
361 }
362}
363
Gilad Arnolddaa27402014-01-23 11:56:17 -0800364bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
365 if (!manifest_parsed_)
366 return false;
367 *out_manifest_p = manifest_;
368 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800369}
370
Jay Srinivasanf4318702012-09-24 11:56:24 -0700371
Darin Petkov9574f7e2011-01-13 10:48:12 -0800372DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800373 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700374 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700375 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800376 uint64_t manifest_size = (metadata_size_ ?
377 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700378
Gilad Arnoldfe133932014-01-14 12:25:50 -0800379 if (!manifest_size) {
380 // Ensure we have data to cover the payload header.
381 if (payload.size() < manifest_offset)
382 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700383
Gilad Arnoldfe133932014-01-14 12:25:50 -0800384 // Validate the magic string.
385 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
386 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700387 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800388 return kMetadataParseError;
389 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800390
391 // Extract the payload version from the metadata.
392 uint64_t major_payload_version;
393 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
394 major_payload_version_size_mismatch);
395 memcpy(&major_payload_version,
396 &payload[GetVersionOffset()],
397 kDeltaVersionSize);
398 // switch big endian to host
399 major_payload_version = be64toh(major_payload_version);
400
401 if (major_payload_version != kSupportedMajorPayloadVersion) {
402 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
403 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700404 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800405 return kMetadataParseError;
406 }
407
408 // Next, parse the manifest size.
409 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
410 manifest_size_size_mismatch);
411 memcpy(&manifest_size,
412 &payload[GetManifestSizeOffset()],
413 kDeltaManifestSizeSize);
414 manifest_size = be64toh(manifest_size); // switch big endian to host
415
416 // If the metadata size is present in install plan, check for it immediately
417 // even before waiting for that many number of bytes to be downloaded in the
418 // payload. This will prevent any attack which relies on us downloading data
419 // beyond the expected metadata size.
420 metadata_size_ = manifest_offset + manifest_size;
421 if (install_plan_->hash_checks_mandatory) {
422 if (install_plan_->metadata_size != metadata_size_) {
423 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
424 << install_plan_->metadata_size
425 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700426 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800427 return kMetadataParseError;
428 }
429 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700430 }
431
432 // Now that we have validated the metadata size, we should wait for the full
433 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800434 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800435 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700436
437 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700438 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700439 // that we just log once (instead of logging n times) if it takes n
440 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800441 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700442 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800443 } else {
444 // For mandatory-cases, we'd have already returned a kMetadataParseError
445 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
446 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
447 << install_plan_->metadata_size
448 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800449 << "Trusting metadata size in payload = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700450 SendUmaStat(ErrorCode::kDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800451 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700452
Jay Srinivasanf4318702012-09-24 11:56:24 -0700453 // We have the full metadata in |payload|. Verify its integrity
454 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800455 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700456 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800457 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800458 // The autoupdate_CatchBadSignatures test checks for this string
459 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800460 LOG(ERROR) << "Mandatory metadata signature validation failed";
461 return kMetadataParseError;
462 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700463
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800464 // For non-mandatory cases, just send a UMA stat.
465 LOG(WARNING) << "Ignoring metadata signature validation failures";
466 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700467 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700468 }
469
Gilad Arnolddaa27402014-01-23 11:56:17 -0800470 // The payload metadata is deemed valid, it's safe to parse the protobuf.
471 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800472 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700473 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800474 return kMetadataParseError;
475 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800476
477 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800478 return kMetadataParseSuccess;
479}
480
Don Garrette410e0f2011-11-10 15:39:01 -0800481// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800482// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700483// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800484bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700485 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700486
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700487 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800488 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800489
490 // Update the total byte downloaded count and the progress logs.
491 total_bytes_received_ += count;
492 UpdateOverallProgress(false, "Completed ");
493
Gilad Arnoldfe133932014-01-14 12:25:50 -0800494 while (!manifest_valid_) {
495 // Read data up to the needed limit; this is either the payload header size,
496 // or the full metadata size (once it becomes known).
497 const bool do_read_header = !metadata_size_;
498 CopyDataToBuffer(&c_bytes, &count,
499 (do_read_header ? GetManifestOffset() :
500 metadata_size_));
501
Gilad Arnolddaa27402014-01-23 11:56:17 -0800502 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700503 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800504 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800505 if (result == kMetadataParseInsufficientData) {
506 // If we just processed the header, make an attempt on the manifest.
507 if (do_read_header && metadata_size_)
508 continue;
509
Don Garrette410e0f2011-11-10 15:39:01 -0800510 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800511 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700512
513 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700514 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700515 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800516 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700517
Gilad Arnoldfe133932014-01-14 12:25:50 -0800518 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800519 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700520 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800521 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700522 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700523
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700524 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700525 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700526 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700527 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800528 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700529 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800530
Allie Woodfdf00512015-03-02 13:34:55 -0800531 // Open source fds if we have a delta payload with minor version 2.
532 if (!install_plan_->is_full_update &&
533 GetMinorVersion() == kSourceMinorPayloadVersion) {
534 if (!OpenSourceRootfs(install_plan_->source_path)) {
535 LOG(ERROR) << "Unable to open source rootfs partition file "
536 << install_plan_->source_path;
537 Close();
538 return false;
539 }
540 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
541 LOG(ERROR) << "Unable to open source kernel partition file "
542 << install_plan_->kernel_source_path;
543 Close();
544 return false;
545 }
546 }
547
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800548 num_rootfs_operations_ = manifest_.install_operations_size();
549 num_total_operations_ =
550 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
551 if (next_operation_num_ > 0)
552 UpdateOverallProgress(true, "Resuming after ");
553 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700554 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800555
556 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700557 // Check if we should cancel the current attempt for any reason.
558 // In this case, *error will have already been populated with the reason
559 // why we're cancelling.
560 if (system_state_->update_attempter()->ShouldCancel(error))
561 return false;
562
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800563 const bool is_kernel_partition =
564 (next_operation_num_ >= num_rootfs_operations_);
Alex Deymoa12ee112015-08-12 22:19:32 -0700565 const InstallOperation& op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800566 is_kernel_partition ?
Alex Deymoa12ee112015-08-12 22:19:32 -0700567 manifest_.kernel_install_operations(next_operation_num_ -
568 num_rootfs_operations_) :
569 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800570
571 CopyDataToBuffer(&c_bytes, &count, op.data_length());
572
573 // Check whether we received all of the next operation's data payload.
574 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700575 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700576
Jay Srinivasanf4318702012-09-24 11:56:24 -0700577 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700578 // Otherwise, keep the old behavior. This serves as a knob to disable
579 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800580 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
581 // we would have already failed in ParsePayloadMetadata method and thus not
582 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700583 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700584 // Note: Validate must be called only if CanPerformInstallOperation is
585 // called. Otherwise, we might be failing operations before even if there
586 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800587 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700588 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800589 if (install_plan_->hash_checks_mandatory) {
590 LOG(ERROR) << "Mandatory operation hash check failed";
591 return false;
592 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700593
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800594 // For non-mandatory cases, just send a UMA stat.
595 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700596 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700597 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700598 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700599 }
600
Darin Petkov45580e42010-10-08 14:02:40 -0700601 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700602 ScopedTerminatorExitUnblocker exit_unblocker =
603 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800604
605 bool op_result;
Alex Deymoa12ee112015-08-12 22:19:32 -0700606 if (op.type() == InstallOperation::REPLACE ||
607 op.type() == InstallOperation::REPLACE_BZ)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800608 op_result = HandleOpResult(
609 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700610 else if (op.type() == InstallOperation::MOVE)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800611 op_result = HandleOpResult(
612 PerformMoveOperation(op, is_kernel_partition), "move", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700613 else if (op.type() == InstallOperation::BSDIFF)
Gilad Arnoldfe133932014-01-14 12:25:50 -0800614 op_result = HandleOpResult(
615 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700616 else if (op.type() == InstallOperation::SOURCE_COPY)
Allie Wood9f6f0a52015-03-30 11:25:47 -0700617 op_result =
618 HandleOpResult(PerformSourceCopyOperation(op, is_kernel_partition),
619 "source_copy", error);
Alex Deymoa12ee112015-08-12 22:19:32 -0700620 else if (op.type() == InstallOperation::SOURCE_BSDIFF)
Allie Wood9f6f0a52015-03-30 11:25:47 -0700621 op_result =
622 HandleOpResult(PerformSourceBsdiffOperation(op, is_kernel_partition),
623 "source_bsdiff", error);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800624 else
625 op_result = HandleOpResult(false, "unknown", error);
626
627 if (!op_result)
628 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800629
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700630 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800631 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700632 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700633 }
Don Garrette410e0f2011-11-10 15:39:01 -0800634 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700635}
636
David Zeuthen8f191b22013-08-06 12:27:50 -0700637bool DeltaPerformer::IsManifestValid() {
638 return manifest_valid_;
639}
640
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700641bool DeltaPerformer::CanPerformInstallOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700642 const chromeos_update_engine::InstallOperation& operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700643 // Move and source_copy operations don't require any data blob, so they can
644 // always be performed.
Alex Deymoa12ee112015-08-12 22:19:32 -0700645 if (operation.type() == InstallOperation::MOVE ||
646 operation.type() == InstallOperation::SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700647 return true;
648
649 // See if we have the entire data blob in the buffer
650 if (operation.data_offset() < buffer_offset_) {
651 LOG(ERROR) << "we threw away data it seems?";
652 return false;
653 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700654
Gilad Arnoldfe133932014-01-14 12:25:50 -0800655 return (operation.data_offset() + operation.data_length() <=
656 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700657}
658
Alex Deymoa12ee112015-08-12 22:19:32 -0700659bool DeltaPerformer::PerformReplaceOperation(const InstallOperation& operation,
660 bool is_kernel_partition) {
661 CHECK(operation.type() == InstallOperation::REPLACE ||
662 operation.type() == InstallOperation::REPLACE_BZ);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700663
664 // Since we delete data off the beginning of the buffer as we use it,
665 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700666 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
667 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700668
Darin Petkov437adc42010-10-07 13:12:24 -0700669 // Extract the signature message if it's in this operation.
670 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700671
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700672 DirectExtentWriter direct_writer;
673 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700674 unique_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700675
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700676 // Since bzip decompression is optional, we have a variable writer that will
677 // point to one of the ExtentWriter objects above.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700678 ExtentWriter* writer = nullptr;
Alex Deymoa12ee112015-08-12 22:19:32 -0700679 if (operation.type() == InstallOperation::REPLACE) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700680 writer = &zero_pad_writer;
Alex Deymoa12ee112015-08-12 22:19:32 -0700681 } else if (operation.type() == InstallOperation::REPLACE_BZ) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700682 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
683 writer = bzip_writer.get();
684 } else {
685 NOTREACHED();
686 }
687
688 // Create a vector of extents to pass to the ExtentWriter.
689 vector<Extent> extents;
690 for (int i = 0; i < operation.dst_extents_size(); i++) {
691 extents.push_back(operation.dst_extents(i));
692 }
693
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800694 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700695
696 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800697 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700698 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700699
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700700 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800701 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700702 return true;
703}
704
Alex Deymoa12ee112015-08-12 22:19:32 -0700705bool DeltaPerformer::PerformMoveOperation(const InstallOperation& operation,
706 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700707 // Calculate buffer size. Note, this function doesn't do a sliding
708 // window to copy in case the source and destination blocks overlap.
709 // If we wanted to do a sliding window, we could program the server
710 // to generate deltas that effectively did a sliding window.
711
712 uint64_t blocks_to_read = 0;
713 for (int i = 0; i < operation.src_extents_size(); i++)
714 blocks_to_read += operation.src_extents(i).num_blocks();
715
716 uint64_t blocks_to_write = 0;
717 for (int i = 0; i < operation.dst_extents_size(); i++)
718 blocks_to_write += operation.dst_extents(i).num_blocks();
719
720 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800721 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700722
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800723 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700724
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700725 // Read in bytes.
726 ssize_t bytes_read = 0;
727 for (int i = 0; i < operation.src_extents_size(); i++) {
728 ssize_t bytes_read_this_iteration = 0;
729 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200730 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700731 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
732 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
733 &buf[bytes_read],
734 bytes,
735 extent.start_block() * block_size_,
736 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700737 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200738 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700739 bytes_read += bytes_read_this_iteration;
740 }
741
742 // Write bytes out.
743 ssize_t bytes_written = 0;
744 for (int i = 0; i < operation.dst_extents_size(); i++) {
745 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200746 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700747 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
748 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
749 &buf[bytes_written],
750 bytes,
751 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200752 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700753 }
754 DCHECK_EQ(bytes_written, bytes_read);
755 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
756 return true;
757}
758
Allie Wood9f6f0a52015-03-30 11:25:47 -0700759namespace {
760
761// Takes |extents| and fills an empty vector |blocks| with a block index for
762// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
763void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
764 vector<uint64_t>* blocks) {
765 for (Extent ext : extents) {
766 for (uint64_t j = 0; j < ext.num_blocks(); j++)
767 blocks->push_back(ext.start_block() + j);
768 }
769}
770
771// Takes |extents| and returns the number of blocks in those extents.
772uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
773 uint64_t sum = 0;
774 for (Extent ext : extents) {
775 sum += ext.num_blocks();
776 }
777 return sum;
778}
779
780} // namespace
781
782bool DeltaPerformer::PerformSourceCopyOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700783 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700784 bool is_kernel_partition) {
785 if (operation.has_src_length())
786 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
787 if (operation.has_dst_length())
788 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
789
790 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
791 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
792 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
793
794 // Create vectors of all the individual src/dst blocks.
795 vector<uint64_t> src_blocks;
796 vector<uint64_t> dst_blocks;
797 ExtentsToBlocks(operation.src_extents(), &src_blocks);
798 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
799 DCHECK_EQ(src_blocks.size(), blocks_to_read);
800 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
801
802 FileDescriptorPtr src_fd =
803 is_kernel_partition ? source_kernel_fd_ : source_fd_;
804 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
805
806 chromeos::Blob buf(block_size_);
807 ssize_t bytes_read = 0;
808 // Read/write one block at a time.
809 for (uint64_t i = 0; i < blocks_to_read; i++) {
810 ssize_t bytes_read_this_iteration = 0;
811 uint64_t src_block = src_blocks[i];
812 uint64_t dst_block = dst_blocks[i];
813
814 // Read in bytes.
815 TEST_AND_RETURN_FALSE(
816 utils::PReadAll(src_fd,
817 buf.data(),
818 block_size_,
819 src_block * block_size_,
820 &bytes_read_this_iteration));
821
822 // Write bytes out.
823 TEST_AND_RETURN_FALSE(
824 utils::PWriteAll(dst_fd,
825 buf.data(),
826 block_size_,
827 dst_block * block_size_));
828
829 bytes_read += bytes_read_this_iteration;
830 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
831 static_cast<ssize_t>(block_size_));
832 }
833 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
834 return true;
835}
836
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700837bool DeltaPerformer::ExtentsToBsdiffPositionsString(
838 const RepeatedPtrField<Extent>& extents,
839 uint64_t block_size,
840 uint64_t full_length,
841 string* positions_string) {
842 string ret;
843 uint64_t length = 0;
844 for (int i = 0; i < extents.size(); i++) {
845 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700846 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700847 uint64_t this_length = min(full_length - length,
848 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700849 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700850 length += this_length;
851 }
852 TEST_AND_RETURN_FALSE(length == full_length);
853 if (!ret.empty())
854 ret.resize(ret.size() - 1); // Strip trailing comma off
855 *positions_string = ret;
856 return true;
857}
858
Alex Deymoa12ee112015-08-12 22:19:32 -0700859bool DeltaPerformer::PerformBsdiffOperation(const InstallOperation& operation,
860 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700861 // Since we delete data off the beginning of the buffer as we use it,
862 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700863 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
864 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700865
866 string input_positions;
867 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
868 block_size_,
869 operation.src_length(),
870 &input_positions));
871 string output_positions;
872 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
873 block_size_,
874 operation.dst_length(),
875 &output_positions));
876
877 string temp_filename;
878 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
879 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700880 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700881 ScopedPathUnlinker path_unlinker(temp_filename);
882 {
883 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
884 ScopedFdCloser fd_closer(&fd);
885 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800886 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700887 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700888
Darin Petkov7f2ec752013-04-03 14:45:19 +0200889 // Update the buffer to release the patch data memory as soon as the patch
890 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800891 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200892
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800893 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700894 vector<string> cmd{kBspatchPath, path, path, temp_filename,
895 input_positions, output_positions};
896
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700897 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700898 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700899 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
900 &return_code, nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700901 TEST_AND_RETURN_FALSE(return_code == 0);
902
903 if (operation.dst_length() % block_size_) {
904 // Zero out rest of final block.
905 // TODO(adlr): build this into bspatch; it's more efficient that way.
906 const Extent& last_extent =
907 operation.dst_extents(operation.dst_extents_size() - 1);
908 const uint64_t end_byte =
909 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
910 const uint64_t begin_byte =
911 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800912 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800913 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700914 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800915 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700916 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700917 return true;
918}
919
Allie Wood9f6f0a52015-03-30 11:25:47 -0700920bool DeltaPerformer::PerformSourceBsdiffOperation(
Alex Deymoa12ee112015-08-12 22:19:32 -0700921 const InstallOperation& operation,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700922 bool is_kernel_partition) {
923 // Since we delete data off the beginning of the buffer as we use it,
924 // the data we need should be exactly at the beginning of the buffer.
925 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
926 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
927 if (operation.has_src_length())
928 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
929 if (operation.has_dst_length())
930 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
931
932 string input_positions;
933 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
934 block_size_,
935 operation.src_length(),
936 &input_positions));
937 string output_positions;
938 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
939 block_size_,
940 operation.dst_length(),
941 &output_positions));
942
943 string temp_filename;
944 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
945 &temp_filename,
946 nullptr));
947 ScopedPathUnlinker path_unlinker(temp_filename);
948 {
949 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
950 ScopedFdCloser fd_closer(&fd);
951 TEST_AND_RETURN_FALSE(
952 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
953 }
954
955 // Update the buffer to release the patch data memory as soon as the patch
956 // file is written out.
957 DiscardBuffer(true);
958
959 const string& src_path = is_kernel_partition ?
960 install_plan_->kernel_source_path :
961 install_plan_->source_path;
962 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
963 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
964 input_positions, output_positions};
965
966 int return_code = 0;
967 TEST_AND_RETURN_FALSE(
Alex Deymo461b2592015-07-24 20:10:52 -0700968 Subprocess::SynchronousExecFlags(cmd, Subprocess::kSearchPath,
969 &return_code, nullptr));
Allie Wood9f6f0a52015-03-30 11:25:47 -0700970 TEST_AND_RETURN_FALSE(return_code == 0);
971 return true;
972}
973
Darin Petkovd7061ab2010-10-06 14:37:09 -0700974bool DeltaPerformer::ExtractSignatureMessage(
Alex Deymoa12ee112015-08-12 22:19:32 -0700975 const InstallOperation& operation) {
976 if (operation.type() != InstallOperation::REPLACE ||
Darin Petkovd7061ab2010-10-06 14:37:09 -0700977 !manifest_.has_signatures_offset() ||
978 manifest_.signatures_offset() != operation.data_offset()) {
979 return false;
980 }
981 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
982 manifest_.signatures_size() == operation.data_length());
983 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
984 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
985 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700986 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700987 buffer_.begin(),
988 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700989
990 // Save the signature blob because if the update is interrupted after the
991 // download phase we don't go through this path anymore. Some alternatives to
992 // consider:
993 //
994 // 1. On resume, re-download the signature blob from the server and re-verify
995 // it.
996 //
997 // 2. Verify the signature as soon as it's received and don't checkpoint the
998 // blob and the signed sha-256 context.
999 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001000 string(signatures_message_data_.begin(),
1001 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001002 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001003 // The hash of all data consumed so far should be verified against the signed
1004 // hash.
1005 signed_hash_context_ = hash_calculator_.GetContext();
1006 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1007 signed_hash_context_))
1008 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001009 LOG(INFO) << "Extracted signature data of size "
1010 << manifest_.signatures_size() << " at "
1011 << manifest_.signatures_offset();
1012 return true;
1013}
1014
David Zeuthene7f89172013-10-31 10:21:04 -07001015bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1016 if (system_state_->hardware()->IsOfficialBuild() ||
1017 utils::FileExists(public_key_path_.c_str()) ||
1018 install_plan_->public_key_rsa.empty())
1019 return false;
1020
1021 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1022 out_tmp_key))
1023 return false;
1024
1025 return true;
1026}
1027
David Zeuthena99981f2013-04-29 13:42:47 -07001028ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001029 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001030
Jay Srinivasanf4318702012-09-24 11:56:24 -07001031 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001032 if (install_plan_->hash_checks_mandatory) {
1033 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001034 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001035 }
1036
1037 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -07001038 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001039 SendUmaStat(ErrorCode::kDownloadMetadataSignatureMissingError);
1040 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001041 }
1042
1043 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001044 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001045 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001046 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001047 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1048 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001049 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001050 }
1051
David Zeuthene7f89172013-10-31 10:21:04 -07001052 // See if we should use the public RSA key in the Omaha response.
1053 base::FilePath path_to_public_key(public_key_path_);
1054 base::FilePath tmp_key;
1055 if (GetPublicKeyFromResponse(&tmp_key))
1056 path_to_public_key = tmp_key;
1057 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1058 if (tmp_key.empty())
1059 tmp_key_remover.set_should_remove(false);
1060
1061 LOG(INFO) << "Verifying metadata hash signature using public key: "
1062 << path_to_public_key.value();
1063
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001064 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001065 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1066 path_to_public_key.value(),
1067 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001068 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001069 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001070 }
1071
Jay Srinivasanf4318702012-09-24 11:56:24 -07001072 OmahaHashCalculator metadata_hasher;
1073 metadata_hasher.Update(metadata, metadata_size);
1074 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001075 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001076 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001077 }
1078
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001079 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001080 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001081 if (calculated_metadata_hash.empty()) {
1082 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001083 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001084 }
1085
Jay Srinivasanf4318702012-09-24 11:56:24 -07001086 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001087 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001088 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001089 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001090 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001091 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001092 }
1093
David Zeuthenbc27aac2013-11-26 11:17:48 -08001094 // The autoupdate_CatchBadSignatures test checks for this string in
1095 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001096 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001097 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001098}
1099
Gilad Arnold21504f02013-05-24 08:51:22 -07001100ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001101 // Perform assorted checks to sanity check the manifest, make sure it
1102 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001103 //
1104 // TODO(garnold) in general, the presence of an old partition hash should be
1105 // the sole indicator for a delta update, as we would generally like update
1106 // payloads to be self contained and not assume an Omaha response to tell us
1107 // that. However, since this requires some massive reengineering of the update
1108 // flow (making filesystem copying happen conditionally only *after*
1109 // downloading and parsing of the update manifest) we'll put it off for now.
1110 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001111 if (install_plan_->is_full_update) {
1112 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1113 LOG(ERROR) << "Purported full payload contains old partition "
1114 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001115 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001116 }
1117
1118 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1119 LOG(ERROR) << "Manifest contains minor version "
1120 << manifest_.minor_version()
1121 << ", but all full payloads should have version "
1122 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001123 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001124 }
1125 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001126 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001127 LOG(ERROR) << "Manifest contains minor version "
1128 << manifest_.minor_version()
1129 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001130 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001131 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001132 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001133 }
1134
1135 // TODO(garnold) we should be adding more and more manifest checks, such as
1136 // partition boundaries etc (see chromium-os:37661).
1137
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001138 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001139}
1140
David Zeuthena99981f2013-04-29 13:42:47 -07001141ErrorCode DeltaPerformer::ValidateOperationHash(
Alex Deymoa12ee112015-08-12 22:19:32 -07001142 const InstallOperation& operation) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001143 if (!operation.data_sha256_hash().size()) {
1144 if (!operation.data_length()) {
1145 // Operations that do not have any data blob won't have any operation hash
1146 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001147 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001148 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001149 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001150 }
1151
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001152 // No hash is present for an operation that has data blobs. This shouldn't
1153 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001154 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001155 // hashes. So if it happens it means either we've turned operation hash
1156 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001157 // One caveat though: The last operation is a dummy signature operation
1158 // that doesn't have a hash at the time the manifest is created. So we
1159 // should not complaint about that operation. This operation can be
1160 // recognized by the fact that it's offset is mentioned in the manifest.
1161 if (manifest_.signatures_offset() &&
1162 manifest_.signatures_offset() == operation.data_offset()) {
1163 LOG(INFO) << "Skipping hash verification for signature operation "
1164 << next_operation_num_ + 1;
1165 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001166 if (install_plan_->hash_checks_mandatory) {
1167 LOG(ERROR) << "Missing mandatory operation hash for operation "
1168 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001169 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001170 }
1171
1172 // For non-mandatory cases, just send a UMA stat.
1173 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1174 << " as there's no operation hash in manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001175 SendUmaStat(ErrorCode::kDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001176 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001177 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001178 }
1179
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001180 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001181 expected_op_hash.assign(operation.data_sha256_hash().data(),
1182 (operation.data_sha256_hash().data() +
1183 operation.data_sha256_hash().size()));
1184
1185 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001186 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001187 if (!operation_hasher.Finalize()) {
1188 LOG(ERROR) << "Unable to compute actual hash of operation "
1189 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001190 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001191 }
1192
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001193 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001194 if (calculated_op_hash != expected_op_hash) {
1195 LOG(ERROR) << "Hash verification failed for operation "
1196 << next_operation_num_ << ". Expected hash = ";
1197 utils::HexDumpVector(expected_op_hash);
1198 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1199 << " bytes at offset: " << operation.data_offset() << " = ";
1200 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001201 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001202 }
1203
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001204 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001205}
1206
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001207#define TEST_AND_RETURN_VAL(_retval, _condition) \
1208 do { \
1209 if (!(_condition)) { \
1210 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1211 return _retval; \
1212 } \
1213 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001214
David Zeuthena99981f2013-04-29 13:42:47 -07001215ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001216 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001217 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001218
1219 // See if we should use the public RSA key in the Omaha response.
1220 base::FilePath path_to_public_key(public_key_path_);
1221 base::FilePath tmp_key;
1222 if (GetPublicKeyFromResponse(&tmp_key))
1223 path_to_public_key = tmp_key;
1224 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1225 if (tmp_key.empty())
1226 tmp_key_remover.set_should_remove(false);
1227
1228 LOG(INFO) << "Verifying payload using public key: "
1229 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001230
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001231 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001232 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001233 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001234 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001235
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001236 // Verifies the payload hash.
1237 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001238 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001239 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001240 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001241 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001242
Darin Petkov437adc42010-10-07 13:12:24 -07001243 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001244 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001245 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001246 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001247 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001248 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001249 !signatures_message_data_.empty());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001250 chromeos::Blob signed_hash_data;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001251 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Alex Deymo923d8fa2014-07-15 17:58:51 -07001252 PayloadVerifier::VerifySignature(
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001253 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001254 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001255 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001256 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001257 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001258 signed_hasher.SetContext(signed_hash_context_));
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.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001261 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001262 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001263 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001264 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001265 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001266 // The autoupdate_CatchBadSignatures test checks for this string
1267 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001268 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001269 "Attached Signature:";
1270 utils::HexDumpVector(signed_hash_data);
1271 LOG(ERROR) << "Computed Signature:";
1272 utils::HexDumpVector(hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001273 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001274 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001275
David Zeuthene7f89172013-10-31 10:21:04 -07001276 LOG(INFO) << "Payload hash matches value in payload.";
1277
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001278 // At this point, we are guaranteed to have downloaded a full payload, i.e
1279 // the one whose size matches the size mentioned in Omaha response. If any
1280 // errors happen after this, it's likely a problem with the payload itself or
1281 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001282 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001283 system_state_->payload_state()->DownloadComplete();
1284
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001285 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001286}
1287
Darin Petkov3aefa862010-12-07 14:45:00 -08001288bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001289 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001290 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001291 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001292 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1293 manifest_.has_new_kernel_info() &&
1294 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001295 *kernel_size = manifest_.new_kernel_info().size();
1296 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001297 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1298 manifest_.new_kernel_info().hash().end());
1299 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1300 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001301 kernel_hash->swap(new_kernel_hash);
1302 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001303 return true;
1304}
1305
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001306namespace {
1307void LogVerifyError(bool is_kern,
1308 const string& local_hash,
1309 const string& expected_hash) {
1310 const char* type = is_kern ? "kernel" : "rootfs";
1311 LOG(ERROR) << "This is a server-side error due to "
1312 << "mismatched delta update image!";
1313 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1314 << "update that must be applied over a " << type << " with "
1315 << "a specific checksum, but the " << type << " we're starting "
1316 << "with doesn't have that checksum! This means that "
1317 << "the delta I've been given doesn't match my existing "
1318 << "system. The " << type << " partition I have has hash: "
1319 << local_hash << " but the update expected me to have "
1320 << expected_hash << " .";
1321 if (is_kern) {
1322 LOG(INFO) << "To get the checksum of a kernel partition on a "
1323 << "booted machine, run this command (change /dev/sda2 "
1324 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1325 << "openssl dgst -sha256 -binary | openssl base64";
1326 } else {
1327 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1328 << "booted machine, run this command (change /dev/sda3 "
1329 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1330 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1331 << "| sed 's/[^0-9]*//') / 256 )) | "
1332 << "openssl dgst -sha256 -binary | openssl base64";
1333 }
1334 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1335 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1336}
1337
1338string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001339 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001340}
1341} // namespace
1342
Darin Petkov698d0412010-10-13 10:59:44 -07001343bool DeltaPerformer::VerifySourcePartitions() {
1344 LOG(INFO) << "Verifying source partitions.";
1345 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001346 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001347 if (manifest_.has_old_kernel_info()) {
1348 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001349 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001350 !install_plan_->source_kernel_hash.empty() &&
1351 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1352 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001353 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001354 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001355 if (!valid) {
1356 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001357 StringForHashBytes(
1358 install_plan_->source_kernel_hash.data(),
1359 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001360 StringForHashBytes(info.hash().data(),
1361 info.hash().size()));
1362 }
1363 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001364 }
1365 if (manifest_.has_old_rootfs_info()) {
1366 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001367 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001368 !install_plan_->source_rootfs_hash.empty() &&
1369 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1370 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001371 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001372 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001373 if (!valid) {
1374 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001375 StringForHashBytes(
1376 install_plan_->source_rootfs_hash.data(),
1377 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001378 StringForHashBytes(info.hash().data(),
1379 info.hash().size()));
1380 }
1381 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001382 }
1383 return true;
1384}
1385
Gilad Arnolddaa27402014-01-23 11:56:17 -08001386void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001387 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001388 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001389 buffer_offset_ += buffer_.size();
1390
1391 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001392 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001393
1394 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001395 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001396}
1397
Darin Petkov0406e402010-10-06 21:33:11 -07001398bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1399 string update_check_response_hash) {
1400 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001401 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1402 next_operation != kUpdateStateOperationInvalid &&
1403 next_operation > 0))
1404 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001405
1406 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001407 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1408 !interrupted_hash.empty() &&
1409 interrupted_hash == update_check_response_hash))
1410 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001411
Darin Petkov61426142010-10-08 11:04:55 -07001412 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001413 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1414 && resumed_update_failures > kMaxResumedUpdateFailures))
1415 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001416
Darin Petkov0406e402010-10-06 21:33:11 -07001417 // Sanity check the rest.
1418 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001419 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1420 next_data_offset >= 0))
1421 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001422
Darin Petkov437adc42010-10-07 13:12:24 -07001423 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001424 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1425 !sha256_context.empty()))
1426 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001427
1428 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001429 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1430 manifest_metadata_size > 0))
1431 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001432
1433 return true;
1434}
1435
Darin Petkov9b230572010-10-08 10:20:09 -07001436bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001437 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1438 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001439 if (!quick) {
1440 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1441 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001442 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001443 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1444 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001445 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001446 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001447 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001448 }
Darin Petkov73058b42010-10-06 16:32:19 -07001449 return true;
1450}
1451
1452bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001453 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001454 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001455 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001456 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001457 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001458 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001459 hash_calculator_.GetContext()));
1460 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1461 buffer_offset_));
1462 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001463
1464 if (next_operation_num_ < num_total_operations_) {
1465 const bool is_kernel_partition =
1466 next_operation_num_ >= num_rootfs_operations_;
Alex Deymoa12ee112015-08-12 22:19:32 -07001467 const InstallOperation& op =
1468 is_kernel_partition
1469 ? manifest_.kernel_install_operations(next_operation_num_ -
1470 num_rootfs_operations_)
1471 : manifest_.install_operations(next_operation_num_);
David Zeuthen41996ad2013-09-24 15:43:24 -07001472 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1473 op.data_length()));
1474 } else {
1475 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1476 0));
1477 }
Darin Petkov0406e402010-10-06 21:33:11 -07001478 }
Darin Petkov73058b42010-10-06 16:32:19 -07001479 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1480 next_operation_num_));
1481 return true;
1482}
1483
Darin Petkov9b230572010-10-08 10:20:09 -07001484bool DeltaPerformer::PrimeUpdateState() {
1485 CHECK(manifest_valid_);
1486 block_size_ = manifest_.block_size();
1487
1488 int64_t next_operation = kUpdateStateOperationInvalid;
1489 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1490 next_operation == kUpdateStateOperationInvalid ||
1491 next_operation <= 0) {
1492 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001493 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001494 return true;
1495 }
1496 next_operation_num_ = next_operation;
1497
1498 // Resuming an update -- load the rest of the update state.
1499 int64_t next_data_offset = -1;
1500 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1501 &next_data_offset) &&
1502 next_data_offset >= 0);
1503 buffer_offset_ = next_data_offset;
1504
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001505 // The signed hash context and the signature blob may be empty if the
1506 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001507 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1508 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001509 string signature_blob;
1510 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1511 signatures_message_data_.assign(signature_blob.begin(),
1512 signature_blob.end());
1513 }
Darin Petkov9b230572010-10-08 10:20:09 -07001514
1515 string hash_context;
1516 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1517 &hash_context) &&
1518 hash_calculator_.SetContext(hash_context));
1519
1520 int64_t manifest_metadata_size = 0;
1521 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1522 &manifest_metadata_size) &&
1523 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001524 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001525
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001526 // Advance the download progress to reflect what doesn't need to be
1527 // re-downloaded.
1528 total_bytes_received_ += buffer_offset_;
1529
Darin Petkov61426142010-10-08 11:04:55 -07001530 // Speculatively count the resume as a failure.
1531 int64_t resumed_update_failures;
1532 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1533 resumed_update_failures++;
1534 } else {
1535 resumed_update_failures = 1;
1536 }
1537 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001538 return true;
1539}
1540
David Zeuthena99981f2013-04-29 13:42:47 -07001541void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001542 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001543}
1544
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001545} // namespace chromeos_update_engine