blob: 87241c04704d66aed935351f9f1604c1ed1cceab [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -07006
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07007#include <endian.h>
8#include <errno.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -07009
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070010#include <algorithm>
11#include <cstring>
Ben Chan02f7c1d2014-10-18 15:18:02 -070012#include <memory>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070013#include <string>
14#include <vector>
15
Ben Chan06c76a42014-09-05 08:21:06 -070016#include <base/files/file_util.h>
Alex Deymo161c4a12014-05-16 15:56:21 -070017#include <base/format_macros.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070018#include <base/strings/string_util.h>
19#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080020#include <chromeos/data_encoding.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070021#include <google/protobuf/repeated_field.h>
22
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070024#include "update_engine/constants.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070025#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include "update_engine/extent_writer.h"
David Zeuthene7f89172013-10-31 10:21:04 -070027#include "update_engine/hardware_interface.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080028#if USE_MTD
29#include "update_engine/mtd_file_descriptor.h"
30#endif
Alex Deymo161c4a12014-05-16 15:56:21 -070031#include "update_engine/payload_constants.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080032#include "update_engine/payload_state_interface.h"
Alex Deymo923d8fa2014-07-15 17:58:51 -070033#include "update_engine/payload_verifier.h"
Darin Petkov73058b42010-10-06 16:32:19 -070034#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070035#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070036#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070037#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070038
Alex Deymo161c4a12014-05-16 15:56:21 -070039using google::protobuf::RepeatedPtrField;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040using std::min;
41using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070042using std::unique_ptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070043using std::vector;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070044
45namespace chromeos_update_engine {
46
Jay Srinivasanf4318702012-09-24 11:56:24 -070047const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
48const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Don Garrett4d039442013-10-28 18:40:06 -070049const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Allie Wood6eeec902015-04-15 10:40:52 -070050const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 2;
Don Garrettb8dd1d92013-11-22 17:40:02 -080051const uint64_t DeltaPerformer::kFullPayloadMinorVersion = 0;
Don Garrett4d039442013-10-28 18:40:06 -070052
Darin Petkovabc7bc02011-02-23 14:39:43 -080053const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
54 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080055const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
56const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
57const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
58const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080059
Allie Woodfdf00512015-03-02 13:34:55 -080060const uint32_t kInPlaceMinorPayloadVersion = 1;
61const uint32_t kSourceMinorPayloadVersion = 2;
Gilad Arnold41e34742015-05-11 11:31:50 -070062const size_t kDefaultChunkSize = 1024 * 1024;
Allie Woodfdf00512015-03-02 13:34:55 -080063
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070064namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070065const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070066const int kMaxResumedUpdateFailures = 10;
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080067#if USE_MTD
68const int kUbiVolumeAttachTimeout = 5 * 60;
69#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080070
71FileDescriptorPtr CreateFileDescriptor(const char* path) {
72 FileDescriptorPtr ret;
73#if USE_MTD
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080074 if (strstr(path, "/dev/ubi") == path) {
75 if (!UbiFileDescriptor::IsUbi(path)) {
76 // The volume might not have been attached at boot time.
77 int volume_no;
78 if (utils::SplitPartitionName(path, nullptr, &volume_no)) {
79 utils::TryAttachingUbiVolume(volume_no, kUbiVolumeAttachTimeout);
80 }
81 }
82 if (UbiFileDescriptor::IsUbi(path)) {
83 LOG(INFO) << path << " is a UBI device.";
84 ret.reset(new UbiFileDescriptor);
85 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080086 } else if (MtdFileDescriptor::IsMtd(path)) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080087 LOG(INFO) << path << " is an MTD device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080088 ret.reset(new MtdFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080089 } else {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080090 LOG(INFO) << path << " is not an MTD nor a UBI device.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080091#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080092 ret.reset(new EintrSafeFileDescriptor);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080093#if USE_MTD
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070094 }
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -080095#endif
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080096 return ret;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070097}
98
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080099// Opens path for read/write. On success returns an open FileDescriptor
100// and sets *err to 0. On failure, sets *err to errno and returns nullptr.
101FileDescriptorPtr OpenFile(const char* path, int* err) {
102 FileDescriptorPtr fd = CreateFileDescriptor(path);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800103 int mode = O_RDWR;
104#if USE_MTD
105 // On NAND devices, we can either read, or write, but not both. So here we
106 // use O_WRONLY.
107 if (UbiFileDescriptor::IsUbi(path) || MtdFileDescriptor::IsMtd(path)) {
108 mode = O_WRONLY;
109 }
110#endif
111 if (!fd->Open(path, mode, 000)) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800112 *err = errno;
113 PLOG(ERROR) << "Unable to open file " << path;
114 return nullptr;
115 }
116 *err = 0;
117 return fd;
118}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700119} // namespace
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700120
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800121
122// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
123// arithmetic.
124static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
125 return part * norm / total;
126}
127
128void DeltaPerformer::LogProgress(const char* message_prefix) {
129 // Format operations total count and percentage.
130 string total_operations_str("?");
131 string completed_percentage_str("");
132 if (num_total_operations_) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700133 total_operations_str = base::StringPrintf("%zu", num_total_operations_);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800134 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
135 completed_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700136 base::StringPrintf(" (%" PRIu64 "%%)",
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800137 IntRatio(next_operation_num_, num_total_operations_,
138 100));
139 }
140
141 // Format download total count and percentage.
142 size_t payload_size = install_plan_->payload_size;
143 string payload_size_str("?");
144 string downloaded_percentage_str("");
145 if (payload_size) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700146 payload_size_str = base::StringPrintf("%zu", payload_size);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800147 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
148 downloaded_percentage_str =
Alex Vakulenko75039d72014-03-25 12:36:28 -0700149 base::StringPrintf(" (%" PRIu64 "%%)",
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800150 IntRatio(total_bytes_received_, payload_size, 100));
151 }
152
153 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
154 << "/" << total_operations_str << " operations"
155 << completed_percentage_str << ", " << total_bytes_received_
156 << "/" << payload_size_str << " bytes downloaded"
157 << downloaded_percentage_str << ", overall progress "
158 << overall_progress_ << "%";
159}
160
161void DeltaPerformer::UpdateOverallProgress(bool force_log,
162 const char* message_prefix) {
163 // Compute our download and overall progress.
164 unsigned new_overall_progress = 0;
165 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
166 progress_weight_dont_add_up);
167 // Only consider download progress if its total size is known; otherwise
168 // adjust the operations weight to compensate for the absence of download
169 // progress. Also, make sure to cap the download portion at
170 // kProgressDownloadWeight, in case we end up downloading more than we
171 // initially expected (this indicates a problem, but could generally happen).
172 // TODO(garnold) the correction of operations weight when we do not have the
173 // total payload size, as well as the conditional guard below, should both be
174 // eliminated once we ensure that the payload_size in the install plan is
175 // always given and is non-zero. This currently isn't the case during unit
176 // tests (see chromium-os:37969).
177 size_t payload_size = install_plan_->payload_size;
178 unsigned actual_operations_weight = kProgressOperationsWeight;
179 if (payload_size)
180 new_overall_progress += min(
181 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
182 kProgressDownloadWeight)),
183 kProgressDownloadWeight);
184 else
185 actual_operations_weight += kProgressDownloadWeight;
186
187 // Only add completed operations if their total number is known; we definitely
188 // expect an update to have at least one operation, so the expectation is that
189 // this will eventually reach |actual_operations_weight|.
190 if (num_total_operations_)
191 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
192 actual_operations_weight);
193
194 // Progress ratio cannot recede, unless our assumptions about the total
195 // payload size, total number of operations, or the monotonicity of progress
196 // is breached.
197 if (new_overall_progress < overall_progress_) {
198 LOG(WARNING) << "progress counter receded from " << overall_progress_
199 << "% down to " << new_overall_progress << "%; this is a bug";
200 force_log = true;
201 }
202 overall_progress_ = new_overall_progress;
203
204 // Update chunk index, log as needed: if forced by called, or we completed a
205 // progress chunk, or a timeout has expired.
206 base::Time curr_time = base::Time::Now();
207 unsigned curr_progress_chunk =
208 overall_progress_ * kProgressLogMaxChunks / 100;
209 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
210 curr_time > forced_progress_log_time_) {
211 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
212 LogProgress(message_prefix);
213 }
214 last_progress_chunk_ = curr_progress_chunk;
215}
216
217
Gilad Arnoldfe133932014-01-14 12:25:50 -0800218size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
219 size_t max) {
220 const size_t count = *count_p;
221 if (!count)
222 return 0; // Special case shortcut.
Alex Deymof329b932014-10-30 01:37:48 -0700223 size_t read_len = min(count, max - buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -0800224 const char* bytes_start = *bytes_p;
225 const char* bytes_end = bytes_start + read_len;
226 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
227 *bytes_p = bytes_end;
228 *count_p = count - read_len;
229 return read_len;
230}
231
232
233bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
234 ErrorCode* error) {
235 if (op_result)
236 return true;
237
238 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
239 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700240 *error = ErrorCode::kDownloadOperationExecutionError;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800241 return false;
242}
243
244
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700245// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
246// it safely. Returns false otherwise.
247bool DeltaPerformer::IsIdempotentOperation(
248 const DeltaArchiveManifest_InstallOperation& op) {
249 if (op.src_extents_size() == 0) {
250 return true;
251 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700252 // When in doubt, it's safe to declare an op non-idempotent. Note that we
253 // could detect other types of idempotent operations here such as a MOVE that
254 // moves blocks onto themselves. However, we rely on the server to not send
255 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700256 ExtentRanges src_ranges;
257 src_ranges.AddRepeatedExtents(op.src_extents());
258 const uint64_t block_count = src_ranges.blocks();
259 src_ranges.SubtractRepeatedExtents(op.dst_extents());
260 return block_count == src_ranges.blocks();
261}
262
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700263int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700264 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800265 fd_ = OpenFile(path, &err);
266 if (fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700267 path_ = path;
268 return -err;
269}
270
271bool DeltaPerformer::OpenKernel(const char* kernel_path) {
272 int err;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800273 kernel_fd_ = OpenFile(kernel_path, &err);
274 if (kernel_fd_)
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700275 kernel_path_ = kernel_path;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800276 return static_cast<bool>(kernel_fd_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700277}
278
Allie Woodfdf00512015-03-02 13:34:55 -0800279bool DeltaPerformer::OpenSourceRootfs(const std::string& source_path) {
280 int err;
281 source_fd_ = OpenFile(source_path.c_str(), &err);
282 return static_cast<bool>(source_fd_);
283}
284
285bool DeltaPerformer::OpenSourceKernel(const std::string& source_kernel_path) {
286 int err;
287 source_kernel_fd_ = OpenFile(source_kernel_path.c_str(), &err);
288 return static_cast<bool>(source_kernel_fd_);
289}
290
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700291int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700292 int err = 0;
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800293 if (!kernel_fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700294 err = errno;
295 PLOG(ERROR) << "Unable to close kernel fd:";
296 }
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800297 if (!fd_->Close()) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700298 err = errno;
299 PLOG(ERROR) << "Unable to close rootfs fd:";
300 }
Allie Woodfdf00512015-03-02 13:34:55 -0800301 if (source_fd_ && !source_fd_->Close()) {
302 err = errno;
303 PLOG(ERROR) << "Unable to close source rootfs fd:";
304 }
305 if (source_kernel_fd_ && !source_kernel_fd_->Close()) {
306 err = errno;
307 PLOG(ERROR) << "Unable to close source kernel fd:";
308 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700309 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800310 fd_.reset(); // Set to invalid so that calls to Open() will fail.
Allie Woodfdf00512015-03-02 13:34:55 -0800311 kernel_fd_.reset();
312 source_fd_.reset();
313 source_kernel_fd_.reset();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700314 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800315 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700316 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
317 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800318 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800319 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700320 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700321}
322
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700323namespace {
324
325void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800326 string sha256 = chromeos::data_encoding::Base64Encode(info.hash());
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800327 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
328 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700329}
330
331void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
332 if (manifest.has_old_kernel_info())
333 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
334 if (manifest.has_old_rootfs_info())
335 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
336 if (manifest.has_new_kernel_info())
337 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
338 if (manifest.has_new_rootfs_info())
339 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
340}
341
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700342} // namespace
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700343
Don Garrett4d039442013-10-28 18:40:06 -0700344uint64_t DeltaPerformer::GetVersionOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800345 // Manifest size is stored right after the magic string and the version.
346 return strlen(kDeltaMagic);
Don Garrett4d039442013-10-28 18:40:06 -0700347}
348
Jay Srinivasanf4318702012-09-24 11:56:24 -0700349uint64_t DeltaPerformer::GetManifestSizeOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800350 // Manifest size is stored right after the magic string and the version.
351 return strlen(kDeltaMagic) + kDeltaVersionSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700352}
353
354uint64_t DeltaPerformer::GetManifestOffset() {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800355 // Actual manifest begins right after the manifest size field.
356 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700357}
358
Gilad Arnoldfe133932014-01-14 12:25:50 -0800359uint64_t DeltaPerformer::GetMetadataSize() const {
Gilad Arnolddaa27402014-01-23 11:56:17 -0800360 return metadata_size_;
361}
362
Allie Woodfdf00512015-03-02 13:34:55 -0800363uint32_t DeltaPerformer::GetMinorVersion() const {
364 if (manifest_.has_minor_version()) {
365 return manifest_.minor_version();
366 } else {
367 return (install_plan_->is_full_update ?
368 kFullPayloadMinorVersion :
369 kSupportedMinorPayloadVersion);
370 }
371}
372
Gilad Arnolddaa27402014-01-23 11:56:17 -0800373bool DeltaPerformer::GetManifest(DeltaArchiveManifest* out_manifest_p) const {
374 if (!manifest_parsed_)
375 return false;
376 *out_manifest_p = manifest_;
377 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800378}
379
Jay Srinivasanf4318702012-09-24 11:56:24 -0700380
Darin Petkov9574f7e2011-01-13 10:48:12 -0800381DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800382 const chromeos::Blob& payload, ErrorCode* error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700383 *error = ErrorCode::kSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700384 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800385 uint64_t manifest_size = (metadata_size_ ?
386 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700387
Gilad Arnoldfe133932014-01-14 12:25:50 -0800388 if (!manifest_size) {
389 // Ensure we have data to cover the payload header.
390 if (payload.size() < manifest_offset)
391 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700392
Gilad Arnoldfe133932014-01-14 12:25:50 -0800393 // Validate the magic string.
394 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
395 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700396 *error = ErrorCode::kDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800397 return kMetadataParseError;
398 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800399
400 // Extract the payload version from the metadata.
401 uint64_t major_payload_version;
402 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
403 major_payload_version_size_mismatch);
404 memcpy(&major_payload_version,
405 &payload[GetVersionOffset()],
406 kDeltaVersionSize);
407 // switch big endian to host
408 major_payload_version = be64toh(major_payload_version);
409
410 if (major_payload_version != kSupportedMajorPayloadVersion) {
411 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
412 << major_payload_version;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700413 *error = ErrorCode::kUnsupportedMajorPayloadVersion;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800414 return kMetadataParseError;
415 }
416
417 // Next, parse the manifest size.
418 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
419 manifest_size_size_mismatch);
420 memcpy(&manifest_size,
421 &payload[GetManifestSizeOffset()],
422 kDeltaManifestSizeSize);
423 manifest_size = be64toh(manifest_size); // switch big endian to host
424
425 // If the metadata size is present in install plan, check for it immediately
426 // even before waiting for that many number of bytes to be downloaded in the
427 // payload. This will prevent any attack which relies on us downloading data
428 // beyond the expected metadata size.
429 metadata_size_ = manifest_offset + manifest_size;
430 if (install_plan_->hash_checks_mandatory) {
431 if (install_plan_->metadata_size != metadata_size_) {
432 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
433 << install_plan_->metadata_size
434 << ") is missing/incorrect, actual = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700435 *error = ErrorCode::kDownloadInvalidMetadataSize;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800436 return kMetadataParseError;
437 }
438 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700439 }
440
441 // Now that we have validated the metadata size, we should wait for the full
442 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800443 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800444 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700445
446 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700447 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700448 // that we just log once (instead of logging n times) if it takes n
449 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800450 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700451 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800452 } else {
453 // For mandatory-cases, we'd have already returned a kMetadataParseError
454 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
455 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
456 << install_plan_->metadata_size
457 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800458 << "Trusting metadata size in payload = " << metadata_size_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700459 SendUmaStat(ErrorCode::kDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800460 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700461
Jay Srinivasanf4318702012-09-24 11:56:24 -0700462 // We have the full metadata in |payload|. Verify its integrity
463 // and authenticity based on the information we have in Omaha response.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800464 *error = ValidateMetadataSignature(payload.data(), metadata_size_);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700465 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800466 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800467 // The autoupdate_CatchBadSignatures test checks for this string
468 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800469 LOG(ERROR) << "Mandatory metadata signature validation failed";
470 return kMetadataParseError;
471 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700472
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800473 // For non-mandatory cases, just send a UMA stat.
474 LOG(WARNING) << "Ignoring metadata signature validation failures";
475 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700476 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700477 }
478
Gilad Arnolddaa27402014-01-23 11:56:17 -0800479 // The payload metadata is deemed valid, it's safe to parse the protobuf.
480 if (!manifest_.ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800481 LOG(ERROR) << "Unable to parse manifest in update file.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700482 *error = ErrorCode::kDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800483 return kMetadataParseError;
484 }
Gilad Arnolddaa27402014-01-23 11:56:17 -0800485
486 manifest_parsed_ = true;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800487 return kMetadataParseSuccess;
488}
489
Don Garrette410e0f2011-11-10 15:39:01 -0800490// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800491// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700492// and stores an action exit code in |error|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800493bool DeltaPerformer::Write(const void* bytes, size_t count, ErrorCode *error) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700494 *error = ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700495
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700496 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800497 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800498
499 // Update the total byte downloaded count and the progress logs.
500 total_bytes_received_ += count;
501 UpdateOverallProgress(false, "Completed ");
502
Gilad Arnoldfe133932014-01-14 12:25:50 -0800503 while (!manifest_valid_) {
504 // Read data up to the needed limit; this is either the payload header size,
505 // or the full metadata size (once it becomes known).
506 const bool do_read_header = !metadata_size_;
507 CopyDataToBuffer(&c_bytes, &count,
508 (do_read_header ? GetManifestOffset() :
509 metadata_size_));
510
Gilad Arnolddaa27402014-01-23 11:56:17 -0800511 MetadataParseResult result = ParsePayloadMetadata(buffer_, error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700512 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800513 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800514 if (result == kMetadataParseInsufficientData) {
515 // If we just processed the header, make an attempt on the manifest.
516 if (do_read_header && metadata_size_)
517 continue;
518
Don Garrette410e0f2011-11-10 15:39:01 -0800519 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800520 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700521
522 // Checks the integrity of the payload manifest.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700523 if ((*error = ValidateManifest()) != ErrorCode::kSuccess)
Gilad Arnold21504f02013-05-24 08:51:22 -0700524 return false;
Gilad Arnolddaa27402014-01-23 11:56:17 -0800525 manifest_valid_ = true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700526
Gilad Arnoldfe133932014-01-14 12:25:50 -0800527 // Clear the download buffer.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800528 DiscardBuffer(false);
Darin Petkov73058b42010-10-06 16:32:19 -0700529 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800530 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700531 << "Unable to save the manifest metadata size.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700532
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700533 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700534 if (!PrimeUpdateState()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700535 *error = ErrorCode::kDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700536 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800537 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700538 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800539
Allie Woodfdf00512015-03-02 13:34:55 -0800540 // Open source fds if we have a delta payload with minor version 2.
541 if (!install_plan_->is_full_update &&
542 GetMinorVersion() == kSourceMinorPayloadVersion) {
543 if (!OpenSourceRootfs(install_plan_->source_path)) {
544 LOG(ERROR) << "Unable to open source rootfs partition file "
545 << install_plan_->source_path;
546 Close();
547 return false;
548 }
549 if (!OpenSourceKernel(install_plan_->kernel_source_path)) {
550 LOG(ERROR) << "Unable to open source kernel partition file "
551 << install_plan_->kernel_source_path;
552 Close();
553 return false;
554 }
555 }
556
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800557 num_rootfs_operations_ = manifest_.install_operations_size();
558 num_total_operations_ =
559 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
560 if (next_operation_num_ > 0)
561 UpdateOverallProgress(true, "Resuming after ");
562 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700563 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800564
565 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700566 // Check if we should cancel the current attempt for any reason.
567 // In this case, *error will have already been populated with the reason
568 // why we're cancelling.
569 if (system_state_->update_attempter()->ShouldCancel(error))
570 return false;
571
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800572 const bool is_kernel_partition =
573 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700574 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800575 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700576 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800577 next_operation_num_ - num_rootfs_operations_) :
578 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800579
580 CopyDataToBuffer(&c_bytes, &count, op.data_length());
581
582 // Check whether we received all of the next operation's data payload.
583 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700584 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700585
Jay Srinivasanf4318702012-09-24 11:56:24 -0700586 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700587 // Otherwise, keep the old behavior. This serves as a knob to disable
588 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800589 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
590 // we would have already failed in ParsePayloadMetadata method and thus not
591 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700592 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700593 // Note: Validate must be called only if CanPerformInstallOperation is
594 // called. Otherwise, we might be failing operations before even if there
595 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800596 *error = ValidateOperationHash(op);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700597 if (*error != ErrorCode::kSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800598 if (install_plan_->hash_checks_mandatory) {
599 LOG(ERROR) << "Mandatory operation hash check failed";
600 return false;
601 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700602
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800603 // For non-mandatory cases, just send a UMA stat.
604 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700605 SendUmaStat(*error);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700606 *error = ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700607 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700608 }
609
Darin Petkov45580e42010-10-08 14:02:40 -0700610 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700611 ScopedTerminatorExitUnblocker exit_unblocker =
612 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800613
614 bool op_result;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700615 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
Gilad Arnoldfe133932014-01-14 12:25:50 -0800616 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ)
617 op_result = HandleOpResult(
618 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
619 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
620 op_result = HandleOpResult(
621 PerformMoveOperation(op, is_kernel_partition), "move", error);
622 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF)
623 op_result = HandleOpResult(
624 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
Allie Wood9f6f0a52015-03-30 11:25:47 -0700625 else if (op.type() ==
626 DeltaArchiveManifest_InstallOperation_Type_SOURCE_COPY)
627 op_result =
628 HandleOpResult(PerformSourceCopyOperation(op, is_kernel_partition),
629 "source_copy", error);
630 else if (op.type() ==
631 DeltaArchiveManifest_InstallOperation_Type_SOURCE_BSDIFF)
632 op_result =
633 HandleOpResult(PerformSourceBsdiffOperation(op, is_kernel_partition),
634 "source_bsdiff", error);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800635 else
636 op_result = HandleOpResult(false, "unknown", error);
637
638 if (!op_result)
639 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800640
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700641 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800642 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700643 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700644 }
Don Garrette410e0f2011-11-10 15:39:01 -0800645 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700646}
647
David Zeuthen8f191b22013-08-06 12:27:50 -0700648bool DeltaPerformer::IsManifestValid() {
649 return manifest_valid_;
650}
651
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700652bool DeltaPerformer::CanPerformInstallOperation(
653 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
654 operation) {
Allie Wood9f6f0a52015-03-30 11:25:47 -0700655 // Move and source_copy operations don't require any data blob, so they can
656 // always be performed.
657 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE ||
658 operation.type() ==
659 DeltaArchiveManifest_InstallOperation_Type_SOURCE_COPY)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700660 return true;
661
662 // See if we have the entire data blob in the buffer
663 if (operation.data_offset() < buffer_offset_) {
664 LOG(ERROR) << "we threw away data it seems?";
665 return false;
666 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700667
Gilad Arnoldfe133932014-01-14 12:25:50 -0800668 return (operation.data_offset() + operation.data_length() <=
669 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700670}
671
672bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700673 const DeltaArchiveManifest_InstallOperation& operation,
674 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700675 CHECK(operation.type() == \
676 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
677 operation.type() == \
678 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
679
680 // Since we delete data off the beginning of the buffer as we use it,
681 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700682 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
683 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700684
Darin Petkov437adc42010-10-07 13:12:24 -0700685 // Extract the signature message if it's in this operation.
686 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700687
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700688 DirectExtentWriter direct_writer;
689 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700690 unique_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700691
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700692 // Since bzip decompression is optional, we have a variable writer that will
693 // point to one of the ExtentWriter objects above.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700694 ExtentWriter* writer = nullptr;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700695 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
696 writer = &zero_pad_writer;
697 } else if (operation.type() ==
698 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
699 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
700 writer = bzip_writer.get();
701 } else {
702 NOTREACHED();
703 }
704
705 // Create a vector of extents to pass to the ExtentWriter.
706 vector<Extent> extents;
707 for (int i = 0; i < operation.dst_extents_size(); i++) {
708 extents.push_back(operation.dst_extents(i));
709 }
710
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800711 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700712
713 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800714 TEST_AND_RETURN_FALSE(writer->Write(buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700715 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700716
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700717 // Update buffer
Gilad Arnolddaa27402014-01-23 11:56:17 -0800718 DiscardBuffer(true);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700719 return true;
720}
721
722bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700723 const DeltaArchiveManifest_InstallOperation& operation,
724 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700725 // Calculate buffer size. Note, this function doesn't do a sliding
726 // window to copy in case the source and destination blocks overlap.
727 // If we wanted to do a sliding window, we could program the server
728 // to generate deltas that effectively did a sliding window.
729
730 uint64_t blocks_to_read = 0;
731 for (int i = 0; i < operation.src_extents_size(); i++)
732 blocks_to_read += operation.src_extents(i).num_blocks();
733
734 uint64_t blocks_to_write = 0;
735 for (int i = 0; i < operation.dst_extents_size(); i++)
736 blocks_to_write += operation.dst_extents(i).num_blocks();
737
738 DCHECK_EQ(blocks_to_write, blocks_to_read);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800739 chromeos::Blob buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700740
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800741 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700742
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700743 // Read in bytes.
744 ssize_t bytes_read = 0;
745 for (int i = 0; i < operation.src_extents_size(); i++) {
746 ssize_t bytes_read_this_iteration = 0;
747 const Extent& extent = operation.src_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::PReadAll(fd,
751 &buf[bytes_read],
752 bytes,
753 extent.start_block() * block_size_,
754 &bytes_read_this_iteration));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700755 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200756 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700757 bytes_read += bytes_read_this_iteration;
758 }
759
Darin Petkov45580e42010-10-08 14:02:40 -0700760 // If this is a non-idempotent operation, request a delayed exit and clear the
761 // update state in case the operation gets interrupted. Do this as late as
762 // possible.
763 if (!IsIdempotentOperation(operation)) {
764 Terminator::set_exit_blocked(true);
765 ResetUpdateProgress(prefs_, true);
766 }
767
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700768 // Write bytes out.
769 ssize_t bytes_written = 0;
770 for (int i = 0; i < operation.dst_extents_size(); i++) {
771 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200772 const size_t bytes = extent.num_blocks() * block_size_;
Allie Wood56873452015-03-27 17:48:40 -0700773 TEST_AND_RETURN_FALSE(extent.start_block() != kSparseHole);
774 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
775 &buf[bytes_written],
776 bytes,
777 extent.start_block() * block_size_));
Darin Petkov8a075a72013-04-25 14:46:09 +0200778 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700779 }
780 DCHECK_EQ(bytes_written, bytes_read);
781 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
782 return true;
783}
784
Allie Wood9f6f0a52015-03-30 11:25:47 -0700785namespace {
786
787// Takes |extents| and fills an empty vector |blocks| with a block index for
788// each block in |extents|. For example, [(3, 2), (8, 1)] would give [3, 4, 8].
789void ExtentsToBlocks(const RepeatedPtrField<Extent>& extents,
790 vector<uint64_t>* blocks) {
791 for (Extent ext : extents) {
792 for (uint64_t j = 0; j < ext.num_blocks(); j++)
793 blocks->push_back(ext.start_block() + j);
794 }
795}
796
797// Takes |extents| and returns the number of blocks in those extents.
798uint64_t GetBlockCount(const RepeatedPtrField<Extent>& extents) {
799 uint64_t sum = 0;
800 for (Extent ext : extents) {
801 sum += ext.num_blocks();
802 }
803 return sum;
804}
805
806} // namespace
807
808bool DeltaPerformer::PerformSourceCopyOperation(
809 const DeltaArchiveManifest_InstallOperation& operation,
810 bool is_kernel_partition) {
811 if (operation.has_src_length())
812 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
813 if (operation.has_dst_length())
814 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
815
816 uint64_t blocks_to_read = GetBlockCount(operation.src_extents());
817 uint64_t blocks_to_write = GetBlockCount(operation.dst_extents());
818 TEST_AND_RETURN_FALSE(blocks_to_write == blocks_to_read);
819
820 // Create vectors of all the individual src/dst blocks.
821 vector<uint64_t> src_blocks;
822 vector<uint64_t> dst_blocks;
823 ExtentsToBlocks(operation.src_extents(), &src_blocks);
824 ExtentsToBlocks(operation.dst_extents(), &dst_blocks);
825 DCHECK_EQ(src_blocks.size(), blocks_to_read);
826 DCHECK_EQ(src_blocks.size(), dst_blocks.size());
827
828 FileDescriptorPtr src_fd =
829 is_kernel_partition ? source_kernel_fd_ : source_fd_;
830 FileDescriptorPtr dst_fd = is_kernel_partition? kernel_fd_ : fd_;
831
832 chromeos::Blob buf(block_size_);
833 ssize_t bytes_read = 0;
834 // Read/write one block at a time.
835 for (uint64_t i = 0; i < blocks_to_read; i++) {
836 ssize_t bytes_read_this_iteration = 0;
837 uint64_t src_block = src_blocks[i];
838 uint64_t dst_block = dst_blocks[i];
839
840 // Read in bytes.
841 TEST_AND_RETURN_FALSE(
842 utils::PReadAll(src_fd,
843 buf.data(),
844 block_size_,
845 src_block * block_size_,
846 &bytes_read_this_iteration));
847
848 // Write bytes out.
849 TEST_AND_RETURN_FALSE(
850 utils::PWriteAll(dst_fd,
851 buf.data(),
852 block_size_,
853 dst_block * block_size_));
854
855 bytes_read += bytes_read_this_iteration;
856 TEST_AND_RETURN_FALSE(bytes_read_this_iteration ==
857 static_cast<ssize_t>(block_size_));
858 }
859 DCHECK_EQ(bytes_read, static_cast<ssize_t>(blocks_to_read * block_size_));
860 return true;
861}
862
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700863bool DeltaPerformer::ExtentsToBsdiffPositionsString(
864 const RepeatedPtrField<Extent>& extents,
865 uint64_t block_size,
866 uint64_t full_length,
867 string* positions_string) {
868 string ret;
869 uint64_t length = 0;
870 for (int i = 0; i < extents.size(); i++) {
871 Extent extent = extents.Get(i);
Allie Wood56873452015-03-27 17:48:40 -0700872 int64_t start = extent.start_block() * block_size;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700873 uint64_t this_length = min(full_length - length,
874 extent.num_blocks() * block_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700875 ret += base::StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700876 length += this_length;
877 }
878 TEST_AND_RETURN_FALSE(length == full_length);
879 if (!ret.empty())
880 ret.resize(ret.size() - 1); // Strip trailing comma off
881 *positions_string = ret;
882 return true;
883}
884
885bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700886 const DeltaArchiveManifest_InstallOperation& operation,
887 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700888 // Since we delete data off the beginning of the buffer as we use it,
889 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700890 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
891 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700892
893 string input_positions;
894 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
895 block_size_,
896 operation.src_length(),
897 &input_positions));
898 string output_positions;
899 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
900 block_size_,
901 operation.dst_length(),
902 &output_positions));
903
904 string temp_filename;
905 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
906 &temp_filename,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700907 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700908 ScopedPathUnlinker path_unlinker(temp_filename);
909 {
910 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
911 ScopedFdCloser fd_closer(&fd);
912 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800913 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700914 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700915
Darin Petkov7f2ec752013-04-03 14:45:19 +0200916 // Update the buffer to release the patch data memory as soon as the patch
917 // file is written out.
Gilad Arnolddaa27402014-01-23 11:56:17 -0800918 DiscardBuffer(true);
Darin Petkov7f2ec752013-04-03 14:45:19 +0200919
Darin Petkov45580e42010-10-08 14:02:40 -0700920 // If this is a non-idempotent operation, request a delayed exit and clear the
921 // update state in case the operation gets interrupted. Do this as late as
922 // possible.
923 if (!IsIdempotentOperation(operation)) {
924 Terminator::set_exit_blocked(true);
925 ResetUpdateProgress(prefs_, true);
926 }
927
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800928 const string& path = is_kernel_partition ? kernel_path_ : path_;
Allie Wood9f6f0a52015-03-30 11:25:47 -0700929 vector<string> cmd{kBspatchPath, path, path, temp_filename,
930 input_positions, output_positions};
931
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700932 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700933 TEST_AND_RETURN_FALSE(
934 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700935 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700936 &return_code,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700937 nullptr));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700938 TEST_AND_RETURN_FALSE(return_code == 0);
939
940 if (operation.dst_length() % block_size_) {
941 // Zero out rest of final block.
942 // TODO(adlr): build this into bspatch; it's more efficient that way.
943 const Extent& last_extent =
944 operation.dst_extents(operation.dst_extents_size() - 1);
945 const uint64_t end_byte =
946 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
947 const uint64_t begin_byte =
948 end_byte - (block_size_ - operation.dst_length() % block_size_);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800949 chromeos::Blob zeros(end_byte - begin_byte);
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800950 FileDescriptorPtr fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700951 TEST_AND_RETURN_FALSE(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800952 utils::PWriteAll(fd, zeros.data(), end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700953 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700954 return true;
955}
956
Allie Wood9f6f0a52015-03-30 11:25:47 -0700957bool DeltaPerformer::PerformSourceBsdiffOperation(
958 const DeltaArchiveManifest_InstallOperation& operation,
959 bool is_kernel_partition) {
960 // Since we delete data off the beginning of the buffer as we use it,
961 // the data we need should be exactly at the beginning of the buffer.
962 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
963 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
964 if (operation.has_src_length())
965 TEST_AND_RETURN_FALSE(operation.src_length() % block_size_ == 0);
966 if (operation.has_dst_length())
967 TEST_AND_RETURN_FALSE(operation.dst_length() % block_size_ == 0);
968
969 string input_positions;
970 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
971 block_size_,
972 operation.src_length(),
973 &input_positions));
974 string output_positions;
975 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
976 block_size_,
977 operation.dst_length(),
978 &output_positions));
979
980 string temp_filename;
981 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
982 &temp_filename,
983 nullptr));
984 ScopedPathUnlinker path_unlinker(temp_filename);
985 {
986 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
987 ScopedFdCloser fd_closer(&fd);
988 TEST_AND_RETURN_FALSE(
989 utils::WriteAll(fd, buffer_.data(), operation.data_length()));
990 }
991
992 // Update the buffer to release the patch data memory as soon as the patch
993 // file is written out.
994 DiscardBuffer(true);
995
996 const string& src_path = is_kernel_partition ?
997 install_plan_->kernel_source_path :
998 install_plan_->source_path;
999 const string& dst_path = is_kernel_partition ? kernel_path_ : path_;
1000 vector<string> cmd{kBspatchPath, src_path, dst_path, temp_filename,
1001 input_positions, output_positions};
1002
1003 int return_code = 0;
1004 TEST_AND_RETURN_FALSE(
1005 Subprocess::SynchronousExecFlags(cmd,
1006 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
1007 &return_code,
1008 nullptr));
1009 TEST_AND_RETURN_FALSE(return_code == 0);
1010 return true;
1011}
1012
Darin Petkovd7061ab2010-10-06 14:37:09 -07001013bool DeltaPerformer::ExtractSignatureMessage(
1014 const DeltaArchiveManifest_InstallOperation& operation) {
1015 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
1016 !manifest_.has_signatures_offset() ||
1017 manifest_.signatures_offset() != operation.data_offset()) {
1018 return false;
1019 }
1020 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
1021 manifest_.signatures_size() == operation.data_length());
1022 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
1023 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
1024 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001025 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -07001026 buffer_.begin(),
1027 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001028
1029 // Save the signature blob because if the update is interrupted after the
1030 // download phase we don't go through this path anymore. Some alternatives to
1031 // consider:
1032 //
1033 // 1. On resume, re-download the signature blob from the server and re-verify
1034 // it.
1035 //
1036 // 2. Verify the signature as soon as it's received and don't checkpoint the
1037 // blob and the signed sha-256 context.
1038 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001039 string(signatures_message_data_.begin(),
1040 signatures_message_data_.end())))
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001041 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -07001042 // The hash of all data consumed so far should be verified against the signed
1043 // hash.
1044 signed_hash_context_ = hash_calculator_.GetContext();
1045 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
1046 signed_hash_context_))
1047 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -07001048 LOG(INFO) << "Extracted signature data of size "
1049 << manifest_.signatures_size() << " at "
1050 << manifest_.signatures_offset();
1051 return true;
1052}
1053
David Zeuthene7f89172013-10-31 10:21:04 -07001054bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
1055 if (system_state_->hardware()->IsOfficialBuild() ||
1056 utils::FileExists(public_key_path_.c_str()) ||
1057 install_plan_->public_key_rsa.empty())
1058 return false;
1059
1060 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
1061 out_tmp_key))
1062 return false;
1063
1064 return true;
1065}
1066
David Zeuthena99981f2013-04-29 13:42:47 -07001067ErrorCode DeltaPerformer::ValidateMetadataSignature(
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001068 const void* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001069
Jay Srinivasanf4318702012-09-24 11:56:24 -07001070 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001071 if (install_plan_->hash_checks_mandatory) {
1072 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001073 return ErrorCode::kDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001074 }
1075
1076 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -07001077 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001078 SendUmaStat(ErrorCode::kDownloadMetadataSignatureMissingError);
1079 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001080 }
1081
1082 // Convert base64-encoded signature to raw bytes.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001083 chromeos::Blob metadata_signature;
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001084 if (!chromeos::data_encoding::Base64Decode(install_plan_->metadata_signature,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001085 &metadata_signature)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001086 LOG(ERROR) << "Unable to decode base64 metadata signature: "
1087 << install_plan_->metadata_signature;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001088 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001089 }
1090
David Zeuthene7f89172013-10-31 10:21:04 -07001091 // See if we should use the public RSA key in the Omaha response.
1092 base::FilePath path_to_public_key(public_key_path_);
1093 base::FilePath tmp_key;
1094 if (GetPublicKeyFromResponse(&tmp_key))
1095 path_to_public_key = tmp_key;
1096 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1097 if (tmp_key.empty())
1098 tmp_key_remover.set_should_remove(false);
1099
1100 LOG(INFO) << "Verifying metadata hash signature using public key: "
1101 << path_to_public_key.value();
1102
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001103 chromeos::Blob expected_metadata_hash;
Alex Deymo923d8fa2014-07-15 17:58:51 -07001104 if (!PayloadVerifier::GetRawHashFromSignature(metadata_signature,
1105 path_to_public_key.value(),
1106 &expected_metadata_hash)) {
Jay Srinivasanf4318702012-09-24 11:56:24 -07001107 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001108 return ErrorCode::kDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001109 }
1110
Jay Srinivasanf4318702012-09-24 11:56:24 -07001111 OmahaHashCalculator metadata_hasher;
1112 metadata_hasher.Update(metadata, metadata_size);
1113 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001114 LOG(ERROR) << "Unable to compute actual hash of manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001115 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001116 }
1117
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001118 chromeos::Blob calculated_metadata_hash = metadata_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001119 PayloadVerifier::PadRSA2048SHA256Hash(&calculated_metadata_hash);
Jay Srinivasanf4318702012-09-24 11:56:24 -07001120 if (calculated_metadata_hash.empty()) {
1121 LOG(ERROR) << "Computed actual hash of metadata is empty.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001122 return ErrorCode::kDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001123 }
1124
Jay Srinivasanf4318702012-09-24 11:56:24 -07001125 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001126 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001127 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001128 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -07001129 utils::HexDumpVector(calculated_metadata_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001130 return ErrorCode::kDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001131 }
1132
David Zeuthenbc27aac2013-11-26 11:17:48 -08001133 // The autoupdate_CatchBadSignatures test checks for this string in
1134 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -07001135 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001136 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001137}
1138
Gilad Arnold21504f02013-05-24 08:51:22 -07001139ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001140 // Perform assorted checks to sanity check the manifest, make sure it
1141 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -07001142 //
1143 // TODO(garnold) in general, the presence of an old partition hash should be
1144 // the sole indicator for a delta update, as we would generally like update
1145 // payloads to be self contained and not assume an Omaha response to tell us
1146 // that. However, since this requires some massive reengineering of the update
1147 // flow (making filesystem copying happen conditionally only *after*
1148 // downloading and parsing of the update manifest) we'll put it off for now.
1149 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -08001150 if (install_plan_->is_full_update) {
1151 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
1152 LOG(ERROR) << "Purported full payload contains old partition "
1153 "hash(es), aborting update";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001154 return ErrorCode::kPayloadMismatchedType;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001155 }
1156
1157 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
1158 LOG(ERROR) << "Manifest contains minor version "
1159 << manifest_.minor_version()
1160 << ", but all full payloads should have version "
1161 << kFullPayloadMinorVersion << ".";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001162 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001163 }
1164 } else {
Allie Woodfdf00512015-03-02 13:34:55 -08001165 if (manifest_.minor_version() != supported_minor_version_) {
Don Garrettb8dd1d92013-11-22 17:40:02 -08001166 LOG(ERROR) << "Manifest contains minor version "
1167 << manifest_.minor_version()
1168 << " not the supported "
Allie Woodfdf00512015-03-02 13:34:55 -08001169 << supported_minor_version_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001170 return ErrorCode::kUnsupportedMinorPayloadVersion;
Don Garrettb8dd1d92013-11-22 17:40:02 -08001171 }
Gilad Arnold21504f02013-05-24 08:51:22 -07001172 }
1173
1174 // TODO(garnold) we should be adding more and more manifest checks, such as
1175 // partition boundaries etc (see chromium-os:37661).
1176
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001177 return ErrorCode::kSuccess;
Gilad Arnold21504f02013-05-24 08:51:22 -07001178}
1179
David Zeuthena99981f2013-04-29 13:42:47 -07001180ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001181 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001182
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001183 if (!operation.data_sha256_hash().size()) {
1184 if (!operation.data_length()) {
1185 // Operations that do not have any data blob won't have any operation hash
1186 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -07001187 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001188 // has already been validated. This is true for both HTTP and HTTPS cases.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001189 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001190 }
1191
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001192 // No hash is present for an operation that has data blobs. This shouldn't
1193 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001194 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001195 // hashes. So if it happens it means either we've turned operation hash
1196 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001197 // One caveat though: The last operation is a dummy signature operation
1198 // that doesn't have a hash at the time the manifest is created. So we
1199 // should not complaint about that operation. This operation can be
1200 // recognized by the fact that it's offset is mentioned in the manifest.
1201 if (manifest_.signatures_offset() &&
1202 manifest_.signatures_offset() == operation.data_offset()) {
1203 LOG(INFO) << "Skipping hash verification for signature operation "
1204 << next_operation_num_ + 1;
1205 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001206 if (install_plan_->hash_checks_mandatory) {
1207 LOG(ERROR) << "Missing mandatory operation hash for operation "
1208 << next_operation_num_ + 1;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001209 return ErrorCode::kDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -08001210 }
1211
1212 // For non-mandatory cases, just send a UMA stat.
1213 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
1214 << " as there's no operation hash in manifest";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001215 SendUmaStat(ErrorCode::kDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001216 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001217 return ErrorCode::kSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001218 }
1219
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001220 chromeos::Blob expected_op_hash;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001221 expected_op_hash.assign(operation.data_sha256_hash().data(),
1222 (operation.data_sha256_hash().data() +
1223 operation.data_sha256_hash().size()));
1224
1225 OmahaHashCalculator operation_hasher;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001226 operation_hasher.Update(buffer_.data(), operation.data_length());
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001227 if (!operation_hasher.Finalize()) {
1228 LOG(ERROR) << "Unable to compute actual hash of operation "
1229 << next_operation_num_;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001230 return ErrorCode::kDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001231 }
1232
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001233 chromeos::Blob calculated_op_hash = operation_hasher.raw_hash();
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001234 if (calculated_op_hash != expected_op_hash) {
1235 LOG(ERROR) << "Hash verification failed for operation "
1236 << next_operation_num_ << ". Expected hash = ";
1237 utils::HexDumpVector(expected_op_hash);
1238 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1239 << " bytes at offset: " << operation.data_offset() << " = ";
1240 utils::HexDumpVector(calculated_op_hash);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001241 return ErrorCode::kDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001242 }
1243
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001244 return ErrorCode::kSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001245}
1246
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001247#define TEST_AND_RETURN_VAL(_retval, _condition) \
1248 do { \
1249 if (!(_condition)) { \
1250 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1251 return _retval; \
1252 } \
1253 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001254
David Zeuthena99981f2013-04-29 13:42:47 -07001255ErrorCode DeltaPerformer::VerifyPayload(
Alex Deymof329b932014-10-30 01:37:48 -07001256 const string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001257 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001258
1259 // See if we should use the public RSA key in the Omaha response.
1260 base::FilePath path_to_public_key(public_key_path_);
1261 base::FilePath tmp_key;
1262 if (GetPublicKeyFromResponse(&tmp_key))
1263 path_to_public_key = tmp_key;
1264 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1265 if (tmp_key.empty())
1266 tmp_key_remover.set_should_remove(false);
1267
1268 LOG(INFO) << "Verifying payload using public key: "
1269 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001270
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001271 // Verifies the download size.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001272 TEST_AND_RETURN_VAL(ErrorCode::kPayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001273 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001274 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001275
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001276 // Verifies the payload hash.
1277 const string& payload_hash_data = hash_calculator_.hash();
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001278 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001279 !payload_hash_data.empty());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001280 TEST_AND_RETURN_VAL(ErrorCode::kPayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001281 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001282
Darin Petkov437adc42010-10-07 13:12:24 -07001283 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001284 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001285 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001286 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001287 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001288 TEST_AND_RETURN_VAL(ErrorCode::kSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001289 !signatures_message_data_.empty());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001290 chromeos::Blob signed_hash_data;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001291 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Alex Deymo923d8fa2014-07-15 17:58:51 -07001292 PayloadVerifier::VerifySignature(
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001293 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001294 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001295 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001296 OmahaHashCalculator signed_hasher;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001297 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001298 signed_hasher.SetContext(signed_hash_context_));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001299 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001300 signed_hasher.Finalize());
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001301 chromeos::Blob hash_data = signed_hasher.raw_hash();
Alex Deymo923d8fa2014-07-15 17:58:51 -07001302 PayloadVerifier::PadRSA2048SHA256Hash(&hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001303 TEST_AND_RETURN_VAL(ErrorCode::kDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001304 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001305 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001306 // The autoupdate_CatchBadSignatures test checks for this string
1307 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001308 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001309 "Attached Signature:";
1310 utils::HexDumpVector(signed_hash_data);
1311 LOG(ERROR) << "Computed Signature:";
1312 utils::HexDumpVector(hash_data);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001313 return ErrorCode::kDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001314 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001315
David Zeuthene7f89172013-10-31 10:21:04 -07001316 LOG(INFO) << "Payload hash matches value in payload.";
1317
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001318 // At this point, we are guaranteed to have downloaded a full payload, i.e
1319 // the one whose size matches the size mentioned in Omaha response. If any
1320 // errors happen after this, it's likely a problem with the payload itself or
1321 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001322 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001323 system_state_->payload_state()->DownloadComplete();
1324
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001325 return ErrorCode::kSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001326}
1327
Darin Petkov3aefa862010-12-07 14:45:00 -08001328bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001329 chromeos::Blob* kernel_hash,
Darin Petkov3aefa862010-12-07 14:45:00 -08001330 uint64_t* rootfs_size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001331 chromeos::Blob* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001332 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1333 manifest_.has_new_kernel_info() &&
1334 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001335 *kernel_size = manifest_.new_kernel_info().size();
1336 *rootfs_size = manifest_.new_rootfs_info().size();
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001337 chromeos::Blob new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1338 manifest_.new_kernel_info().hash().end());
1339 chromeos::Blob new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1340 manifest_.new_rootfs_info().hash().end());
Darin Petkov3aefa862010-12-07 14:45:00 -08001341 kernel_hash->swap(new_kernel_hash);
1342 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001343 return true;
1344}
1345
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001346namespace {
1347void LogVerifyError(bool is_kern,
1348 const string& local_hash,
1349 const string& expected_hash) {
1350 const char* type = is_kern ? "kernel" : "rootfs";
1351 LOG(ERROR) << "This is a server-side error due to "
1352 << "mismatched delta update image!";
1353 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1354 << "update that must be applied over a " << type << " with "
1355 << "a specific checksum, but the " << type << " we're starting "
1356 << "with doesn't have that checksum! This means that "
1357 << "the delta I've been given doesn't match my existing "
1358 << "system. The " << type << " partition I have has hash: "
1359 << local_hash << " but the update expected me to have "
1360 << expected_hash << " .";
1361 if (is_kern) {
1362 LOG(INFO) << "To get the checksum of a kernel partition on a "
1363 << "booted machine, run this command (change /dev/sda2 "
1364 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1365 << "openssl dgst -sha256 -binary | openssl base64";
1366 } else {
1367 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1368 << "booted machine, run this command (change /dev/sda3 "
1369 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1370 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1371 << "| sed 's/[^0-9]*//') / 256 )) | "
1372 << "openssl dgst -sha256 -binary | openssl base64";
1373 }
1374 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1375 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1376}
1377
1378string StringForHashBytes(const void* bytes, size_t size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001379 return chromeos::data_encoding::Base64Encode(bytes, size);
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001380}
1381} // namespace
1382
Darin Petkov698d0412010-10-13 10:59:44 -07001383bool DeltaPerformer::VerifySourcePartitions() {
1384 LOG(INFO) << "Verifying source partitions.";
1385 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001386 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001387 if (manifest_.has_old_kernel_info()) {
1388 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001389 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001390 !install_plan_->source_kernel_hash.empty() &&
1391 install_plan_->source_kernel_hash.size() == info.hash().size() &&
1392 memcmp(install_plan_->source_kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001393 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001394 install_plan_->source_kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001395 if (!valid) {
1396 LogVerifyError(true,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001397 StringForHashBytes(
1398 install_plan_->source_kernel_hash.data(),
1399 install_plan_->source_kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001400 StringForHashBytes(info.hash().data(),
1401 info.hash().size()));
1402 }
1403 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001404 }
1405 if (manifest_.has_old_rootfs_info()) {
1406 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001407 bool valid =
Allie Woodeb9e6d82015-04-17 13:55:30 -07001408 !install_plan_->source_rootfs_hash.empty() &&
1409 install_plan_->source_rootfs_hash.size() == info.hash().size() &&
1410 memcmp(install_plan_->source_rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001411 info.hash().data(),
Allie Woodeb9e6d82015-04-17 13:55:30 -07001412 install_plan_->source_rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001413 if (!valid) {
1414 LogVerifyError(false,
Allie Woodeb9e6d82015-04-17 13:55:30 -07001415 StringForHashBytes(
1416 install_plan_->source_rootfs_hash.data(),
1417 install_plan_->source_rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001418 StringForHashBytes(info.hash().data(),
1419 info.hash().size()));
1420 }
1421 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001422 }
1423 return true;
1424}
1425
Gilad Arnolddaa27402014-01-23 11:56:17 -08001426void DeltaPerformer::DiscardBuffer(bool do_advance_offset) {
Gilad Arnoldfe133932014-01-14 12:25:50 -08001427 // Update the buffer offset.
Gilad Arnolddaa27402014-01-23 11:56:17 -08001428 if (do_advance_offset)
Gilad Arnoldfe133932014-01-14 12:25:50 -08001429 buffer_offset_ += buffer_.size();
1430
1431 // Hash the content.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001432 hash_calculator_.Update(buffer_.data(), buffer_.size());
Gilad Arnoldfe133932014-01-14 12:25:50 -08001433
1434 // Swap content with an empty vector to ensure that all memory is released.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001435 chromeos::Blob().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001436}
1437
Darin Petkov0406e402010-10-06 21:33:11 -07001438bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1439 string update_check_response_hash) {
1440 int64_t next_operation = kUpdateStateOperationInvalid;
Alex Deymo3310b222015-03-30 15:59:07 -07001441 if (!(prefs->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) &&
1442 next_operation != kUpdateStateOperationInvalid &&
1443 next_operation > 0))
1444 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001445
1446 string interrupted_hash;
Alex Deymo3310b222015-03-30 15:59:07 -07001447 if (!(prefs->GetString(kPrefsUpdateCheckResponseHash, &interrupted_hash) &&
1448 !interrupted_hash.empty() &&
1449 interrupted_hash == update_check_response_hash))
1450 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001451
Darin Petkov61426142010-10-08 11:04:55 -07001452 int64_t resumed_update_failures;
Alex Deymo3310b222015-03-30 15:59:07 -07001453 if (!(prefs->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)
1454 && resumed_update_failures > kMaxResumedUpdateFailures))
1455 return false;
Darin Petkov61426142010-10-08 11:04:55 -07001456
Darin Petkov0406e402010-10-06 21:33:11 -07001457 // Sanity check the rest.
1458 int64_t next_data_offset = -1;
Alex Deymo3310b222015-03-30 15:59:07 -07001459 if (!(prefs->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset) &&
1460 next_data_offset >= 0))
1461 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001462
Darin Petkov437adc42010-10-07 13:12:24 -07001463 string sha256_context;
Alex Deymo3310b222015-03-30 15:59:07 -07001464 if (!(prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1465 !sha256_context.empty()))
1466 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001467
1468 int64_t manifest_metadata_size = 0;
Alex Deymo3310b222015-03-30 15:59:07 -07001469 if (!(prefs->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size) &&
1470 manifest_metadata_size > 0))
1471 return false;
Darin Petkov0406e402010-10-06 21:33:11 -07001472
1473 return true;
1474}
1475
Darin Petkov9b230572010-10-08 10:20:09 -07001476bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001477 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1478 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001479 if (!quick) {
1480 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1481 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001482 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001483 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1484 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001485 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001486 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001487 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001488 }
Darin Petkov73058b42010-10-06 16:32:19 -07001489 return true;
1490}
1491
1492bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001493 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001494 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001495 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001496 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001497 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001498 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001499 hash_calculator_.GetContext()));
1500 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1501 buffer_offset_));
1502 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001503
1504 if (next_operation_num_ < num_total_operations_) {
1505 const bool is_kernel_partition =
1506 next_operation_num_ >= num_rootfs_operations_;
1507 const DeltaArchiveManifest_InstallOperation &op =
1508 is_kernel_partition ?
1509 manifest_.kernel_install_operations(
1510 next_operation_num_ - num_rootfs_operations_) :
1511 manifest_.install_operations(next_operation_num_);
1512 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1513 op.data_length()));
1514 } else {
1515 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1516 0));
1517 }
Darin Petkov0406e402010-10-06 21:33:11 -07001518 }
Darin Petkov73058b42010-10-06 16:32:19 -07001519 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1520 next_operation_num_));
1521 return true;
1522}
1523
Darin Petkov9b230572010-10-08 10:20:09 -07001524bool DeltaPerformer::PrimeUpdateState() {
1525 CHECK(manifest_valid_);
1526 block_size_ = manifest_.block_size();
1527
1528 int64_t next_operation = kUpdateStateOperationInvalid;
1529 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1530 next_operation == kUpdateStateOperationInvalid ||
1531 next_operation <= 0) {
1532 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001533 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001534 return true;
1535 }
1536 next_operation_num_ = next_operation;
1537
1538 // Resuming an update -- load the rest of the update state.
1539 int64_t next_data_offset = -1;
1540 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1541 &next_data_offset) &&
1542 next_data_offset >= 0);
1543 buffer_offset_ = next_data_offset;
1544
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001545 // The signed hash context and the signature blob may be empty if the
1546 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001547 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1548 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001549 string signature_blob;
1550 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1551 signatures_message_data_.assign(signature_blob.begin(),
1552 signature_blob.end());
1553 }
Darin Petkov9b230572010-10-08 10:20:09 -07001554
1555 string hash_context;
1556 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1557 &hash_context) &&
1558 hash_calculator_.SetContext(hash_context));
1559
1560 int64_t manifest_metadata_size = 0;
1561 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1562 &manifest_metadata_size) &&
1563 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001564 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001565
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001566 // Advance the download progress to reflect what doesn't need to be
1567 // re-downloaded.
1568 total_bytes_received_ += buffer_offset_;
1569
Darin Petkov61426142010-10-08 11:04:55 -07001570 // Speculatively count the resume as a failure.
1571 int64_t resumed_update_failures;
1572 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1573 resumed_update_failures++;
1574 } else {
1575 resumed_update_failures = 1;
1576 }
1577 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001578 return true;
1579}
1580
David Zeuthena99981f2013-04-29 13:42:47 -07001581void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001582 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001583}
1584
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001585} // namespace chromeos_update_engine