blob: e2fc834b08e0e262c7e91a06af0fbec9e2f060a1 [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>
12#include <string>
13#include <vector>
14
David Zeuthene7f89172013-10-31 10:21:04 -070015#include <base/file_util.h>
Chris Masoned903c3b2011-05-12 15:35:46 -070016#include <base/memory/scoped_ptr.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070017#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040018#include <base/stringprintf.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include <google/protobuf/repeated_field.h>
20
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070021#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070022#include "update_engine/constants.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070024#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070025#include "update_engine/extent_writer.h"
26#include "update_engine/graph_types.h"
David Zeuthene7f89172013-10-31 10:21:04 -070027#include "update_engine/hardware_interface.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070028#include "update_engine/payload_signer.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080029#include "update_engine/payload_state_interface.h"
Darin Petkov73058b42010-10-06 16:32:19 -070030#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070031#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070032#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070033#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070034
35using std::min;
36using std::string;
37using std::vector;
38using google::protobuf::RepeatedPtrField;
39
40namespace chromeos_update_engine {
41
Jay Srinivasanf4318702012-09-24 11:56:24 -070042const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
43const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Don Garrett4d039442013-10-28 18:40:06 -070044const uint64_t DeltaPerformer::kSupportedMajorPayloadVersion = 1;
Don Garrettb8dd1d92013-11-22 17:40:02 -080045const uint64_t DeltaPerformer::kSupportedMinorPayloadVersion = 1;
46const uint64_t DeltaPerformer::kFullPayloadMinorVersion = 0;
Don Garrett4d039442013-10-28 18:40:06 -070047
Darin Petkovabc7bc02011-02-23 14:39:43 -080048const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
49 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080050const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
51const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
52const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
53const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080054
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070055namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070056const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070057const int kMaxResumedUpdateFailures = 10;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070058// Opens path for read/write, put the fd into *fd. On success returns true
59// and sets *err to 0. On failure, returns false and sets *err to errno.
60bool OpenFile(const char* path, int* fd, int* err) {
61 if (*fd != -1) {
62 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
63 *err = EINVAL;
64 return false;
65 }
66 *fd = open(path, O_RDWR, 000);
67 if (*fd < 0) {
68 *err = errno;
69 PLOG(ERROR) << "Unable to open file " << path;
70 return false;
71 }
72 *err = 0;
73 return true;
74}
75
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070076} // namespace {}
77
Gilad Arnold8a86fa52013-01-15 12:35:05 -080078
79// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
80// arithmetic.
81static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
82 return part * norm / total;
83}
84
85void DeltaPerformer::LogProgress(const char* message_prefix) {
86 // Format operations total count and percentage.
87 string total_operations_str("?");
88 string completed_percentage_str("");
89 if (num_total_operations_) {
90 total_operations_str = StringPrintf("%zu", num_total_operations_);
91 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
92 completed_percentage_str =
93 StringPrintf(" (%llu%%)",
94 IntRatio(next_operation_num_, num_total_operations_,
95 100));
96 }
97
98 // Format download total count and percentage.
99 size_t payload_size = install_plan_->payload_size;
100 string payload_size_str("?");
101 string downloaded_percentage_str("");
102 if (payload_size) {
103 payload_size_str = StringPrintf("%zu", payload_size);
104 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
105 downloaded_percentage_str =
106 StringPrintf(" (%llu%%)",
107 IntRatio(total_bytes_received_, payload_size, 100));
108 }
109
110 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
111 << "/" << total_operations_str << " operations"
112 << completed_percentage_str << ", " << total_bytes_received_
113 << "/" << payload_size_str << " bytes downloaded"
114 << downloaded_percentage_str << ", overall progress "
115 << overall_progress_ << "%";
116}
117
118void DeltaPerformer::UpdateOverallProgress(bool force_log,
119 const char* message_prefix) {
120 // Compute our download and overall progress.
121 unsigned new_overall_progress = 0;
122 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
123 progress_weight_dont_add_up);
124 // Only consider download progress if its total size is known; otherwise
125 // adjust the operations weight to compensate for the absence of download
126 // progress. Also, make sure to cap the download portion at
127 // kProgressDownloadWeight, in case we end up downloading more than we
128 // initially expected (this indicates a problem, but could generally happen).
129 // TODO(garnold) the correction of operations weight when we do not have the
130 // total payload size, as well as the conditional guard below, should both be
131 // eliminated once we ensure that the payload_size in the install plan is
132 // always given and is non-zero. This currently isn't the case during unit
133 // tests (see chromium-os:37969).
134 size_t payload_size = install_plan_->payload_size;
135 unsigned actual_operations_weight = kProgressOperationsWeight;
136 if (payload_size)
137 new_overall_progress += min(
138 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
139 kProgressDownloadWeight)),
140 kProgressDownloadWeight);
141 else
142 actual_operations_weight += kProgressDownloadWeight;
143
144 // Only add completed operations if their total number is known; we definitely
145 // expect an update to have at least one operation, so the expectation is that
146 // this will eventually reach |actual_operations_weight|.
147 if (num_total_operations_)
148 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
149 actual_operations_weight);
150
151 // Progress ratio cannot recede, unless our assumptions about the total
152 // payload size, total number of operations, or the monotonicity of progress
153 // is breached.
154 if (new_overall_progress < overall_progress_) {
155 LOG(WARNING) << "progress counter receded from " << overall_progress_
156 << "% down to " << new_overall_progress << "%; this is a bug";
157 force_log = true;
158 }
159 overall_progress_ = new_overall_progress;
160
161 // Update chunk index, log as needed: if forced by called, or we completed a
162 // progress chunk, or a timeout has expired.
163 base::Time curr_time = base::Time::Now();
164 unsigned curr_progress_chunk =
165 overall_progress_ * kProgressLogMaxChunks / 100;
166 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
167 curr_time > forced_progress_log_time_) {
168 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
169 LogProgress(message_prefix);
170 }
171 last_progress_chunk_ = curr_progress_chunk;
172}
173
174
Gilad Arnoldfe133932014-01-14 12:25:50 -0800175size_t DeltaPerformer::CopyDataToBuffer(const char** bytes_p, size_t* count_p,
176 size_t max) {
177 const size_t count = *count_p;
178 if (!count)
179 return 0; // Special case shortcut.
180 size_t read_len = std::min(count, max - buffer_.size());
181 const char* bytes_start = *bytes_p;
182 const char* bytes_end = bytes_start + read_len;
183 buffer_.insert(buffer_.end(), bytes_start, bytes_end);
184 *bytes_p = bytes_end;
185 *count_p = count - read_len;
186 return read_len;
187}
188
189
190bool DeltaPerformer::HandleOpResult(bool op_result, const char* op_type_name,
191 ErrorCode* error) {
192 if (op_result)
193 return true;
194
195 LOG(ERROR) << "Failed to perform " << op_type_name << " operation "
196 << next_operation_num_;
197 *error = kErrorCodeDownloadOperationExecutionError;
198 return false;
199}
200
201
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700202// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
203// it safely. Returns false otherwise.
204bool DeltaPerformer::IsIdempotentOperation(
205 const DeltaArchiveManifest_InstallOperation& op) {
206 if (op.src_extents_size() == 0) {
207 return true;
208 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700209 // When in doubt, it's safe to declare an op non-idempotent. Note that we
210 // could detect other types of idempotent operations here such as a MOVE that
211 // moves blocks onto themselves. However, we rely on the server to not send
212 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700213 ExtentRanges src_ranges;
214 src_ranges.AddRepeatedExtents(op.src_extents());
215 const uint64_t block_count = src_ranges.blocks();
216 src_ranges.SubtractRepeatedExtents(op.dst_extents());
217 return block_count == src_ranges.blocks();
218}
219
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700220int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700221 int err;
222 if (OpenFile(path, &fd_, &err))
223 path_ = path;
224 return -err;
225}
226
227bool DeltaPerformer::OpenKernel(const char* kernel_path) {
228 int err;
229 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
230 if (success)
231 kernel_path_ = kernel_path;
232 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700233}
234
235int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700236 int err = 0;
237 if (close(kernel_fd_) == -1) {
238 err = errno;
239 PLOG(ERROR) << "Unable to close kernel fd:";
240 }
241 if (close(fd_) == -1) {
242 err = errno;
243 PLOG(ERROR) << "Unable to close rootfs fd:";
244 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700245 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800246 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700247 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800248 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700249 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
250 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800251 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800252 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700253 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700254}
255
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700256namespace {
257
258void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
259 string sha256;
260 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
261 info.hash().size(),
262 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800263 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
264 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700265 } else {
266 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
267 }
268}
269
270void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
271 if (manifest.has_old_kernel_info())
272 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
273 if (manifest.has_old_rootfs_info())
274 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
275 if (manifest.has_new_kernel_info())
276 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
277 if (manifest.has_new_rootfs_info())
278 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
279}
280
281} // namespace {}
282
Don Garrett4d039442013-10-28 18:40:06 -0700283uint64_t DeltaPerformer::GetVersionOffset() {
284 // Manifest size is stored right after the magic string and the version.
285 return strlen(kDeltaMagic);
286}
287
Jay Srinivasanf4318702012-09-24 11:56:24 -0700288uint64_t DeltaPerformer::GetManifestSizeOffset() {
289 // Manifest size is stored right after the magic string and the version.
290 return strlen(kDeltaMagic) + kDeltaVersionSize;
291}
292
293uint64_t DeltaPerformer::GetManifestOffset() {
294 // Actual manifest begins right after the manifest size field.
295 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
296}
297
Gilad Arnoldfe133932014-01-14 12:25:50 -0800298uint64_t DeltaPerformer::GetMetadataSize() const {
299 return metadata_size_;
300}
301
Jay Srinivasanf4318702012-09-24 11:56:24 -0700302
Darin Petkov9574f7e2011-01-13 10:48:12 -0800303DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
304 const std::vector<char>& payload,
305 DeltaArchiveManifest* manifest,
David Zeuthena99981f2013-04-29 13:42:47 -0700306 ErrorCode* error) {
307 *error = kErrorCodeSuccess;
Jay Srinivasanf4318702012-09-24 11:56:24 -0700308 const uint64_t manifest_offset = GetManifestOffset();
Gilad Arnoldfe133932014-01-14 12:25:50 -0800309 uint64_t manifest_size = (metadata_size_ ?
310 metadata_size_ - manifest_offset : 0);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700311
Gilad Arnoldfe133932014-01-14 12:25:50 -0800312 if (!manifest_size) {
313 // Ensure we have data to cover the payload header.
314 if (payload.size() < manifest_offset)
315 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700316
Gilad Arnoldfe133932014-01-14 12:25:50 -0800317 // Validate the magic string.
318 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
319 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
320 *error = kErrorCodeDownloadInvalidMetadataMagicString;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800321 return kMetadataParseError;
322 }
Gilad Arnoldfe133932014-01-14 12:25:50 -0800323
324 // Extract the payload version from the metadata.
325 uint64_t major_payload_version;
326 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
327 major_payload_version_size_mismatch);
328 memcpy(&major_payload_version,
329 &payload[GetVersionOffset()],
330 kDeltaVersionSize);
331 // switch big endian to host
332 major_payload_version = be64toh(major_payload_version);
333
334 if (major_payload_version != kSupportedMajorPayloadVersion) {
335 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
336 << major_payload_version;
337 *error = kErrorCodeUnsupportedMajorPayloadVersion;
338 return kMetadataParseError;
339 }
340
341 // Next, parse the manifest size.
342 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
343 manifest_size_size_mismatch);
344 memcpy(&manifest_size,
345 &payload[GetManifestSizeOffset()],
346 kDeltaManifestSizeSize);
347 manifest_size = be64toh(manifest_size); // switch big endian to host
348
349 // If the metadata size is present in install plan, check for it immediately
350 // even before waiting for that many number of bytes to be downloaded in the
351 // payload. This will prevent any attack which relies on us downloading data
352 // beyond the expected metadata size.
353 metadata_size_ = manifest_offset + manifest_size;
354 if (install_plan_->hash_checks_mandatory) {
355 if (install_plan_->metadata_size != metadata_size_) {
356 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
357 << install_plan_->metadata_size
358 << ") is missing/incorrect, actual = " << metadata_size_;
359 *error = kErrorCodeDownloadInvalidMetadataSize;
360 return kMetadataParseError;
361 }
362 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700363 }
364
365 // Now that we have validated the metadata size, we should wait for the full
366 // metadata to be read in before we can parse it.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800367 if (payload.size() < metadata_size_)
Darin Petkov9574f7e2011-01-13 10:48:12 -0800368 return kMetadataParseInsufficientData;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700369
370 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700371 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700372 // that we just log once (instead of logging n times) if it takes n
373 // DeltaPerformer::Write calls to download the full manifest.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800374 if (install_plan_->metadata_size == metadata_size_) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700375 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800376 } else {
377 // For mandatory-cases, we'd have already returned a kMetadataParseError
378 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
379 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
380 << install_plan_->metadata_size
381 << ") in Omaha response as validation is not mandatory. "
Gilad Arnoldfe133932014-01-14 12:25:50 -0800382 << "Trusting metadata size in payload = " << metadata_size_;
David Zeuthena99981f2013-04-29 13:42:47 -0700383 SendUmaStat(kErrorCodeDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800384 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700385
Jay Srinivasanf4318702012-09-24 11:56:24 -0700386 // We have the full metadata in |payload|. Verify its integrity
387 // and authenticity based on the information we have in Omaha response.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800388 *error = ValidateMetadataSignature(&payload[0], metadata_size_);
David Zeuthena99981f2013-04-29 13:42:47 -0700389 if (*error != kErrorCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800390 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800391 // The autoupdate_CatchBadSignatures test checks for this string
392 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800393 LOG(ERROR) << "Mandatory metadata signature validation failed";
394 return kMetadataParseError;
395 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700396
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800397 // For non-mandatory cases, just send a UMA stat.
398 LOG(WARNING) << "Ignoring metadata signature validation failures";
399 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700400 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700401 }
402
Jay Srinivasanf4318702012-09-24 11:56:24 -0700403 // The metadata in |payload| is deemed valid. So, it's now safe to
404 // parse the protobuf.
405 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800406 LOG(ERROR) << "Unable to parse manifest in update file.";
David Zeuthena99981f2013-04-29 13:42:47 -0700407 *error = kErrorCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800408 return kMetadataParseError;
409 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800410 return kMetadataParseSuccess;
411}
412
413
Don Garrette410e0f2011-11-10 15:39:01 -0800414// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800415// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700416// and stores an action exit code in |error|.
417bool DeltaPerformer::Write(const void* bytes, size_t count,
David Zeuthena99981f2013-04-29 13:42:47 -0700418 ErrorCode *error) {
419 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700420
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700421 const char* c_bytes = reinterpret_cast<const char*>(bytes);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800422 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800423
424 // Update the total byte downloaded count and the progress logs.
425 total_bytes_received_ += count;
426 UpdateOverallProgress(false, "Completed ");
427
Gilad Arnoldfe133932014-01-14 12:25:50 -0800428 while (!manifest_valid_) {
429 // Read data up to the needed limit; this is either the payload header size,
430 // or the full metadata size (once it becomes known).
431 const bool do_read_header = !metadata_size_;
432 CopyDataToBuffer(&c_bytes, &count,
433 (do_read_header ? GetManifestOffset() :
434 metadata_size_));
435
Darin Petkov9574f7e2011-01-13 10:48:12 -0800436 MetadataParseResult result = ParsePayloadMetadata(buffer_,
437 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700438 error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700439 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800440 return false;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800441 if (result == kMetadataParseInsufficientData) {
442 // If we just processed the header, make an attempt on the manifest.
443 if (do_read_header && metadata_size_)
444 continue;
445
Don Garrette410e0f2011-11-10 15:39:01 -0800446 return true;
Gilad Arnoldfe133932014-01-14 12:25:50 -0800447 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700448
449 // Checks the integrity of the payload manifest.
450 if ((*error = ValidateManifest()) != kErrorCodeSuccess)
451 return false;
452
Gilad Arnoldfe133932014-01-14 12:25:50 -0800453 // Clear the download buffer.
454 DiscardBuffer();
Darin Petkov73058b42010-10-06 16:32:19 -0700455 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800456 metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700457 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700458 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700459
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700460 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700461 if (!PrimeUpdateState()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700462 *error = kErrorCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700463 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800464 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700465 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800466
467 num_rootfs_operations_ = manifest_.install_operations_size();
468 num_total_operations_ =
469 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
470 if (next_operation_num_ > 0)
471 UpdateOverallProgress(true, "Resuming after ");
472 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700473 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800474
475 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700476 // Check if we should cancel the current attempt for any reason.
477 // In this case, *error will have already been populated with the reason
478 // why we're cancelling.
479 if (system_state_->update_attempter()->ShouldCancel(error))
480 return false;
481
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800482 const bool is_kernel_partition =
483 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700484 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800485 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700486 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800487 next_operation_num_ - num_rootfs_operations_) :
488 manifest_.install_operations(next_operation_num_);
Gilad Arnoldfe133932014-01-14 12:25:50 -0800489
490 CopyDataToBuffer(&c_bytes, &count, op.data_length());
491
492 // Check whether we received all of the next operation's data payload.
493 if (!CanPerformInstallOperation(op))
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700494 return true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700495
Jay Srinivasanf4318702012-09-24 11:56:24 -0700496 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700497 // Otherwise, keep the old behavior. This serves as a knob to disable
498 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800499 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
500 // we would have already failed in ParsePayloadMetadata method and thus not
501 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700502 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700503 // Note: Validate must be called only if CanPerformInstallOperation is
504 // called. Otherwise, we might be failing operations before even if there
505 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800506 *error = ValidateOperationHash(op);
David Zeuthena99981f2013-04-29 13:42:47 -0700507 if (*error != kErrorCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800508 if (install_plan_->hash_checks_mandatory) {
509 LOG(ERROR) << "Mandatory operation hash check failed";
510 return false;
511 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700512
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800513 // For non-mandatory cases, just send a UMA stat.
514 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700515 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700516 *error = kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700517 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700518 }
519
Darin Petkov45580e42010-10-08 14:02:40 -0700520 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700521 ScopedTerminatorExitUnblocker exit_unblocker =
522 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800523
524 bool op_result;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700525 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
Gilad Arnoldfe133932014-01-14 12:25:50 -0800526 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ)
527 op_result = HandleOpResult(
528 PerformReplaceOperation(op, is_kernel_partition), "replace", error);
529 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
530 op_result = HandleOpResult(
531 PerformMoveOperation(op, is_kernel_partition), "move", error);
532 else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF)
533 op_result = HandleOpResult(
534 PerformBsdiffOperation(op, is_kernel_partition), "bsdiff", error);
535 else
536 op_result = HandleOpResult(false, "unknown", error);
537
538 if (!op_result)
539 return false;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800540
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700541 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800542 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700543 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700544 }
Don Garrette410e0f2011-11-10 15:39:01 -0800545 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700546}
547
David Zeuthen8f191b22013-08-06 12:27:50 -0700548bool DeltaPerformer::IsManifestValid() {
549 return manifest_valid_;
550}
551
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700552bool DeltaPerformer::CanPerformInstallOperation(
553 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
554 operation) {
555 // Move operations don't require any data blob, so they can always
556 // be performed
557 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
558 return true;
559
560 // See if we have the entire data blob in the buffer
561 if (operation.data_offset() < buffer_offset_) {
562 LOG(ERROR) << "we threw away data it seems?";
563 return false;
564 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700565
Gilad Arnoldfe133932014-01-14 12:25:50 -0800566 return (operation.data_offset() + operation.data_length() <=
567 buffer_offset_ + buffer_.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700568}
569
570bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700571 const DeltaArchiveManifest_InstallOperation& operation,
572 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700573 CHECK(operation.type() == \
574 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
575 operation.type() == \
576 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
577
578 // Since we delete data off the beginning of the buffer as we use it,
579 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700580 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
581 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700582
Darin Petkov437adc42010-10-07 13:12:24 -0700583 // Extract the signature message if it's in this operation.
584 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700585
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700586 DirectExtentWriter direct_writer;
587 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
588 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700589
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700590 // Since bzip decompression is optional, we have a variable writer that will
591 // point to one of the ExtentWriter objects above.
592 ExtentWriter* writer = NULL;
593 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
594 writer = &zero_pad_writer;
595 } else if (operation.type() ==
596 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
597 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
598 writer = bzip_writer.get();
599 } else {
600 NOTREACHED();
601 }
602
603 // Create a vector of extents to pass to the ExtentWriter.
604 vector<Extent> extents;
605 for (int i = 0; i < operation.dst_extents_size(); i++) {
606 extents.push_back(operation.dst_extents(i));
607 }
608
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700609 int fd = is_kernel_partition ? kernel_fd_ : fd_;
610
611 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700612 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
613 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700614
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700615 // Update buffer
Gilad Arnoldfe133932014-01-14 12:25:50 -0800616 DiscardBuffer();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700617 return true;
618}
619
620bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700621 const DeltaArchiveManifest_InstallOperation& operation,
622 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700623 // Calculate buffer size. Note, this function doesn't do a sliding
624 // window to copy in case the source and destination blocks overlap.
625 // If we wanted to do a sliding window, we could program the server
626 // to generate deltas that effectively did a sliding window.
627
628 uint64_t blocks_to_read = 0;
629 for (int i = 0; i < operation.src_extents_size(); i++)
630 blocks_to_read += operation.src_extents(i).num_blocks();
631
632 uint64_t blocks_to_write = 0;
633 for (int i = 0; i < operation.dst_extents_size(); i++)
634 blocks_to_write += operation.dst_extents(i).num_blocks();
635
636 DCHECK_EQ(blocks_to_write, blocks_to_read);
637 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700638
639 int fd = is_kernel_partition ? kernel_fd_ : fd_;
640
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700641 // Read in bytes.
642 ssize_t bytes_read = 0;
643 for (int i = 0; i < operation.src_extents_size(); i++) {
644 ssize_t bytes_read_this_iteration = 0;
645 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200646 const size_t bytes = extent.num_blocks() * block_size_;
647 if (extent.start_block() == kSparseHole) {
648 bytes_read_this_iteration = bytes;
649 memset(&buf[bytes_read], 0, bytes);
650 } else {
651 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
652 &buf[bytes_read],
653 bytes,
654 extent.start_block() * block_size_,
655 &bytes_read_this_iteration));
656 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700657 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200658 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700659 bytes_read += bytes_read_this_iteration;
660 }
661
Darin Petkov45580e42010-10-08 14:02:40 -0700662 // If this is a non-idempotent operation, request a delayed exit and clear the
663 // update state in case the operation gets interrupted. Do this as late as
664 // possible.
665 if (!IsIdempotentOperation(operation)) {
666 Terminator::set_exit_blocked(true);
667 ResetUpdateProgress(prefs_, true);
668 }
669
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700670 // Write bytes out.
671 ssize_t bytes_written = 0;
672 for (int i = 0; i < operation.dst_extents_size(); i++) {
673 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200674 const size_t bytes = extent.num_blocks() * block_size_;
675 if (extent.start_block() == kSparseHole) {
Darin Petkov741a8222013-05-02 10:02:34 +0200676 DCHECK(buf.begin() + bytes_written ==
677 std::search_n(buf.begin() + bytes_written,
678 buf.begin() + bytes_written + bytes,
679 bytes, 0));
Darin Petkov8a075a72013-04-25 14:46:09 +0200680 } else {
681 TEST_AND_RETURN_FALSE(
682 utils::PWriteAll(fd,
683 &buf[bytes_written],
684 bytes,
685 extent.start_block() * block_size_));
686 }
687 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700688 }
689 DCHECK_EQ(bytes_written, bytes_read);
690 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
691 return true;
692}
693
694bool DeltaPerformer::ExtentsToBsdiffPositionsString(
695 const RepeatedPtrField<Extent>& extents,
696 uint64_t block_size,
697 uint64_t full_length,
698 string* positions_string) {
699 string ret;
700 uint64_t length = 0;
701 for (int i = 0; i < extents.size(); i++) {
702 Extent extent = extents.Get(i);
703 int64_t start = extent.start_block();
704 uint64_t this_length = min(full_length - length,
705 extent.num_blocks() * block_size);
706 if (start == static_cast<int64_t>(kSparseHole))
707 start = -1;
708 else
709 start *= block_size;
710 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
711 length += this_length;
712 }
713 TEST_AND_RETURN_FALSE(length == full_length);
714 if (!ret.empty())
715 ret.resize(ret.size() - 1); // Strip trailing comma off
716 *positions_string = ret;
717 return true;
718}
719
720bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700721 const DeltaArchiveManifest_InstallOperation& operation,
722 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700723 // Since we delete data off the beginning of the buffer as we use it,
724 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700725 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
726 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700727
728 string input_positions;
729 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
730 block_size_,
731 operation.src_length(),
732 &input_positions));
733 string output_positions;
734 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
735 block_size_,
736 operation.dst_length(),
737 &output_positions));
738
739 string temp_filename;
740 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
741 &temp_filename,
742 NULL));
743 ScopedPathUnlinker path_unlinker(temp_filename);
744 {
745 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
746 ScopedFdCloser fd_closer(&fd);
747 TEST_AND_RETURN_FALSE(
748 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
749 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700750
Darin Petkov7f2ec752013-04-03 14:45:19 +0200751 // Update the buffer to release the patch data memory as soon as the patch
752 // file is written out.
Gilad Arnoldfe133932014-01-14 12:25:50 -0800753 DiscardBuffer();
Darin Petkov7f2ec752013-04-03 14:45:19 +0200754
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700755 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Darin Petkov3d1670d2013-07-12 14:37:06 +0200756 const string path = StringPrintf("/proc/self/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700757
Darin Petkov45580e42010-10-08 14:02:40 -0700758 // If this is a non-idempotent operation, request a delayed exit and clear the
759 // update state in case the operation gets interrupted. Do this as late as
760 // possible.
761 if (!IsIdempotentOperation(operation)) {
762 Terminator::set_exit_blocked(true);
763 ResetUpdateProgress(prefs_, true);
764 }
765
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700766 vector<string> cmd;
767 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700768 cmd.push_back(path);
769 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700770 cmd.push_back(temp_filename);
771 cmd.push_back(input_positions);
772 cmd.push_back(output_positions);
773 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700774 TEST_AND_RETURN_FALSE(
775 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700776 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700777 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700778 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700779 TEST_AND_RETURN_FALSE(return_code == 0);
780
781 if (operation.dst_length() % block_size_) {
782 // Zero out rest of final block.
783 // TODO(adlr): build this into bspatch; it's more efficient that way.
784 const Extent& last_extent =
785 operation.dst_extents(operation.dst_extents_size() - 1);
786 const uint64_t end_byte =
787 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
788 const uint64_t begin_byte =
789 end_byte - (block_size_ - operation.dst_length() % block_size_);
790 vector<char> zeros(end_byte - begin_byte);
791 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700792 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700793 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700794 return true;
795}
796
Darin Petkovd7061ab2010-10-06 14:37:09 -0700797bool DeltaPerformer::ExtractSignatureMessage(
798 const DeltaArchiveManifest_InstallOperation& operation) {
799 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
800 !manifest_.has_signatures_offset() ||
801 manifest_.signatures_offset() != operation.data_offset()) {
802 return false;
803 }
804 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
805 manifest_.signatures_size() == operation.data_length());
806 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
807 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
808 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700809 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700810 buffer_.begin(),
811 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700812
813 // Save the signature blob because if the update is interrupted after the
814 // download phase we don't go through this path anymore. Some alternatives to
815 // consider:
816 //
817 // 1. On resume, re-download the signature blob from the server and re-verify
818 // it.
819 //
820 // 2. Verify the signature as soon as it's received and don't checkpoint the
821 // blob and the signed sha-256 context.
822 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
823 string(&signatures_message_data_[0],
824 signatures_message_data_.size())))
825 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700826 // The hash of all data consumed so far should be verified against the signed
827 // hash.
828 signed_hash_context_ = hash_calculator_.GetContext();
829 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
830 signed_hash_context_))
831 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700832 LOG(INFO) << "Extracted signature data of size "
833 << manifest_.signatures_size() << " at "
834 << manifest_.signatures_offset();
835 return true;
836}
837
David Zeuthene7f89172013-10-31 10:21:04 -0700838bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
839 if (system_state_->hardware()->IsOfficialBuild() ||
840 utils::FileExists(public_key_path_.c_str()) ||
841 install_plan_->public_key_rsa.empty())
842 return false;
843
844 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
845 out_tmp_key))
846 return false;
847
848 return true;
849}
850
David Zeuthena99981f2013-04-29 13:42:47 -0700851ErrorCode DeltaPerformer::ValidateMetadataSignature(
Jay Srinivasanf4318702012-09-24 11:56:24 -0700852 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700853
Jay Srinivasanf4318702012-09-24 11:56:24 -0700854 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800855 if (install_plan_->hash_checks_mandatory) {
856 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700857 return kErrorCodeDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800858 }
859
860 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700861 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
David Zeuthena99981f2013-04-29 13:42:47 -0700862 SendUmaStat(kErrorCodeDownloadMetadataSignatureMissingError);
863 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700864 }
865
866 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700867 vector<char> metadata_signature;
868 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
869 &metadata_signature)) {
870 LOG(ERROR) << "Unable to decode base64 metadata signature: "
871 << install_plan_->metadata_signature;
David Zeuthena99981f2013-04-29 13:42:47 -0700872 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700873 }
874
David Zeuthene7f89172013-10-31 10:21:04 -0700875 // See if we should use the public RSA key in the Omaha response.
876 base::FilePath path_to_public_key(public_key_path_);
877 base::FilePath tmp_key;
878 if (GetPublicKeyFromResponse(&tmp_key))
879 path_to_public_key = tmp_key;
880 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
881 if (tmp_key.empty())
882 tmp_key_remover.set_should_remove(false);
883
884 LOG(INFO) << "Verifying metadata hash signature using public key: "
885 << path_to_public_key.value();
886
Jay Srinivasanf4318702012-09-24 11:56:24 -0700887 vector<char> expected_metadata_hash;
888 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
David Zeuthene7f89172013-10-31 10:21:04 -0700889 path_to_public_key.value(),
Jay Srinivasanf4318702012-09-24 11:56:24 -0700890 &expected_metadata_hash)) {
891 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
David Zeuthena99981f2013-04-29 13:42:47 -0700892 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700893 }
894
Jay Srinivasanf4318702012-09-24 11:56:24 -0700895 OmahaHashCalculator metadata_hasher;
896 metadata_hasher.Update(metadata, metadata_size);
897 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700898 LOG(ERROR) << "Unable to compute actual hash of manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700899 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700900 }
901
Jay Srinivasanf4318702012-09-24 11:56:24 -0700902 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
903 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
904 if (calculated_metadata_hash.empty()) {
905 LOG(ERROR) << "Computed actual hash of metadata is empty.";
David Zeuthena99981f2013-04-29 13:42:47 -0700906 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700907 }
908
Jay Srinivasanf4318702012-09-24 11:56:24 -0700909 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700910 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700911 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700912 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700913 utils::HexDumpVector(calculated_metadata_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700914 return kErrorCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700915 }
916
David Zeuthenbc27aac2013-11-26 11:17:48 -0800917 // The autoupdate_CatchBadSignatures test checks for this string in
918 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -0700919 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
David Zeuthena99981f2013-04-29 13:42:47 -0700920 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700921}
922
Gilad Arnold21504f02013-05-24 08:51:22 -0700923ErrorCode DeltaPerformer::ValidateManifest() {
Don Garrettb8dd1d92013-11-22 17:40:02 -0800924 // Perform assorted checks to sanity check the manifest, make sure it
925 // matches data from other sources, and that it is a supported version.
Gilad Arnold21504f02013-05-24 08:51:22 -0700926 //
927 // TODO(garnold) in general, the presence of an old partition hash should be
928 // the sole indicator for a delta update, as we would generally like update
929 // payloads to be self contained and not assume an Omaha response to tell us
930 // that. However, since this requires some massive reengineering of the update
931 // flow (making filesystem copying happen conditionally only *after*
932 // downloading and parsing of the update manifest) we'll put it off for now.
933 // See chromium-os:7597 for further discussion.
Don Garrettb8dd1d92013-11-22 17:40:02 -0800934 if (install_plan_->is_full_update) {
935 if (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info()) {
936 LOG(ERROR) << "Purported full payload contains old partition "
937 "hash(es), aborting update";
938 return kErrorCodePayloadMismatchedType;
939 }
940
941 if (manifest_.minor_version() != kFullPayloadMinorVersion) {
942 LOG(ERROR) << "Manifest contains minor version "
943 << manifest_.minor_version()
944 << ", but all full payloads should have version "
945 << kFullPayloadMinorVersion << ".";
946 return kErrorCodeUnsupportedMinorPayloadVersion;
947 }
948 } else {
949 if (manifest_.minor_version() != kSupportedMinorPayloadVersion) {
950 LOG(ERROR) << "Manifest contains minor version "
951 << manifest_.minor_version()
952 << " not the supported "
953 << kSupportedMinorPayloadVersion;
954 return kErrorCodeUnsupportedMinorPayloadVersion;
955 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700956 }
957
958 // TODO(garnold) we should be adding more and more manifest checks, such as
959 // partition boundaries etc (see chromium-os:37661).
960
961 return kErrorCodeSuccess;
962}
963
David Zeuthena99981f2013-04-29 13:42:47 -0700964ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800965 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700966
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700967 if (!operation.data_sha256_hash().size()) {
968 if (!operation.data_length()) {
969 // Operations that do not have any data blob won't have any operation hash
970 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700971 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800972 // has already been validated. This is true for both HTTP and HTTPS cases.
David Zeuthena99981f2013-04-29 13:42:47 -0700973 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700974 }
975
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800976 // No hash is present for an operation that has data blobs. This shouldn't
977 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700978 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800979 // hashes. So if it happens it means either we've turned operation hash
980 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700981 // One caveat though: The last operation is a dummy signature operation
982 // that doesn't have a hash at the time the manifest is created. So we
983 // should not complaint about that operation. This operation can be
984 // recognized by the fact that it's offset is mentioned in the manifest.
985 if (manifest_.signatures_offset() &&
986 manifest_.signatures_offset() == operation.data_offset()) {
987 LOG(INFO) << "Skipping hash verification for signature operation "
988 << next_operation_num_ + 1;
989 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800990 if (install_plan_->hash_checks_mandatory) {
991 LOG(ERROR) << "Missing mandatory operation hash for operation "
992 << next_operation_num_ + 1;
David Zeuthena99981f2013-04-29 13:42:47 -0700993 return kErrorCodeDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800994 }
995
996 // For non-mandatory cases, just send a UMA stat.
997 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
998 << " as there's no operation hash in manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700999 SendUmaStat(kErrorCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001000 }
David Zeuthena99981f2013-04-29 13:42:47 -07001001 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001002 }
1003
1004 vector<char> expected_op_hash;
1005 expected_op_hash.assign(operation.data_sha256_hash().data(),
1006 (operation.data_sha256_hash().data() +
1007 operation.data_sha256_hash().size()));
1008
1009 OmahaHashCalculator operation_hasher;
1010 operation_hasher.Update(&buffer_[0], operation.data_length());
1011 if (!operation_hasher.Finalize()) {
1012 LOG(ERROR) << "Unable to compute actual hash of operation "
1013 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -07001014 return kErrorCodeDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001015 }
1016
1017 vector<char> calculated_op_hash = operation_hasher.raw_hash();
1018 if (calculated_op_hash != expected_op_hash) {
1019 LOG(ERROR) << "Hash verification failed for operation "
1020 << next_operation_num_ << ". Expected hash = ";
1021 utils::HexDumpVector(expected_op_hash);
1022 LOG(ERROR) << "Calculated hash over " << operation.data_length()
1023 << " bytes at offset: " << operation.data_offset() << " = ";
1024 utils::HexDumpVector(calculated_op_hash);
David Zeuthena99981f2013-04-29 13:42:47 -07001025 return kErrorCodeDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -07001026 }
1027
David Zeuthena99981f2013-04-29 13:42:47 -07001028 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001029}
1030
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001031#define TEST_AND_RETURN_VAL(_retval, _condition) \
1032 do { \
1033 if (!(_condition)) { \
1034 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
1035 return _retval; \
1036 } \
1037 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001038
David Zeuthena99981f2013-04-29 13:42:47 -07001039ErrorCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -07001040 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001041 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -07001042
1043 // See if we should use the public RSA key in the Omaha response.
1044 base::FilePath path_to_public_key(public_key_path_);
1045 base::FilePath tmp_key;
1046 if (GetPublicKeyFromResponse(&tmp_key))
1047 path_to_public_key = tmp_key;
1048 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1049 if (tmp_key.empty())
1050 tmp_key_remover.set_should_remove(false);
1051
1052 LOG(INFO) << "Verifying payload using public key: "
1053 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001054
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001055 // Verifies the download size.
David Zeuthena99981f2013-04-29 13:42:47 -07001056 TEST_AND_RETURN_VAL(kErrorCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001057 update_check_response_size ==
Gilad Arnoldfe133932014-01-14 12:25:50 -08001058 metadata_size_ + buffer_offset_);
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001059
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001060 // Verifies the payload hash.
1061 const string& payload_hash_data = hash_calculator_.hash();
David Zeuthena99981f2013-04-29 13:42:47 -07001062 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001063 !payload_hash_data.empty());
David Zeuthena99981f2013-04-29 13:42:47 -07001064 TEST_AND_RETURN_VAL(kErrorCodePayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001065 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001066
Darin Petkov437adc42010-10-07 13:12:24 -07001067 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001068 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001069 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
David Zeuthena99981f2013-04-29 13:42:47 -07001070 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001071 }
David Zeuthena99981f2013-04-29 13:42:47 -07001072 TEST_AND_RETURN_VAL(kErrorCodeSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001073 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -07001074 vector<char> signed_hash_data;
David Zeuthena99981f2013-04-29 13:42:47 -07001075 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001076 PayloadSigner::VerifySignature(
1077 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001078 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001079 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001080 OmahaHashCalculator signed_hasher;
David Zeuthena99981f2013-04-29 13:42:47 -07001081 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001082 signed_hasher.SetContext(signed_hash_context_));
David Zeuthena99981f2013-04-29 13:42:47 -07001083 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001084 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -07001085 vector<char> hash_data = signed_hasher.raw_hash();
1086 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -07001087 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001088 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001089 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001090 // The autoupdate_CatchBadSignatures test checks for this string
1091 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001092 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001093 "Attached Signature:";
1094 utils::HexDumpVector(signed_hash_data);
1095 LOG(ERROR) << "Computed Signature:";
1096 utils::HexDumpVector(hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -07001097 return kErrorCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001098 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001099
David Zeuthene7f89172013-10-31 10:21:04 -07001100 LOG(INFO) << "Payload hash matches value in payload.";
1101
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001102 // At this point, we are guaranteed to have downloaded a full payload, i.e
1103 // the one whose size matches the size mentioned in Omaha response. If any
1104 // errors happen after this, it's likely a problem with the payload itself or
1105 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001106 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001107 system_state_->payload_state()->DownloadComplete();
1108
David Zeuthena99981f2013-04-29 13:42:47 -07001109 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001110}
1111
Darin Petkov3aefa862010-12-07 14:45:00 -08001112bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
1113 vector<char>* kernel_hash,
1114 uint64_t* rootfs_size,
1115 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001116 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1117 manifest_.has_new_kernel_info() &&
1118 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001119 *kernel_size = manifest_.new_kernel_info().size();
1120 *rootfs_size = manifest_.new_rootfs_info().size();
1121 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1122 manifest_.new_kernel_info().hash().end());
1123 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1124 manifest_.new_rootfs_info().hash().end());
1125 kernel_hash->swap(new_kernel_hash);
1126 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001127 return true;
1128}
1129
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001130namespace {
1131void LogVerifyError(bool is_kern,
1132 const string& local_hash,
1133 const string& expected_hash) {
1134 const char* type = is_kern ? "kernel" : "rootfs";
1135 LOG(ERROR) << "This is a server-side error due to "
1136 << "mismatched delta update image!";
1137 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1138 << "update that must be applied over a " << type << " with "
1139 << "a specific checksum, but the " << type << " we're starting "
1140 << "with doesn't have that checksum! This means that "
1141 << "the delta I've been given doesn't match my existing "
1142 << "system. The " << type << " partition I have has hash: "
1143 << local_hash << " but the update expected me to have "
1144 << expected_hash << " .";
1145 if (is_kern) {
1146 LOG(INFO) << "To get the checksum of a kernel partition on a "
1147 << "booted machine, run this command (change /dev/sda2 "
1148 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1149 << "openssl dgst -sha256 -binary | openssl base64";
1150 } else {
1151 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1152 << "booted machine, run this command (change /dev/sda3 "
1153 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1154 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1155 << "| sed 's/[^0-9]*//') / 256 )) | "
1156 << "openssl dgst -sha256 -binary | openssl base64";
1157 }
1158 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1159 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1160}
1161
1162string StringForHashBytes(const void* bytes, size_t size) {
1163 string ret;
1164 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1165 ret = "<unknown>";
1166 }
1167 return ret;
1168}
1169} // namespace
1170
Darin Petkov698d0412010-10-13 10:59:44 -07001171bool DeltaPerformer::VerifySourcePartitions() {
1172 LOG(INFO) << "Verifying source partitions.";
1173 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001174 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001175 if (manifest_.has_old_kernel_info()) {
1176 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001177 bool valid =
1178 !install_plan_->kernel_hash.empty() &&
1179 install_plan_->kernel_hash.size() == info.hash().size() &&
1180 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001181 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001182 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001183 if (!valid) {
1184 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001185 StringForHashBytes(install_plan_->kernel_hash.data(),
1186 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001187 StringForHashBytes(info.hash().data(),
1188 info.hash().size()));
1189 }
1190 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001191 }
1192 if (manifest_.has_old_rootfs_info()) {
1193 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001194 bool valid =
1195 !install_plan_->rootfs_hash.empty() &&
1196 install_plan_->rootfs_hash.size() == info.hash().size() &&
1197 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001198 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001199 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001200 if (!valid) {
1201 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001202 StringForHashBytes(install_plan_->rootfs_hash.data(),
1203 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001204 StringForHashBytes(info.hash().data(),
1205 info.hash().size()));
1206 }
1207 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001208 }
1209 return true;
1210}
1211
Gilad Arnoldfe133932014-01-14 12:25:50 -08001212void DeltaPerformer::DiscardBuffer() {
1213 // Update the buffer offset.
1214 if (manifest_valid_)
1215 buffer_offset_ += buffer_.size();
1216
1217 // Hash the content.
1218 hash_calculator_.Update(&buffer_[0], buffer_.size());
1219
1220 // Swap content with an empty vector to ensure that all memory is released.
1221 vector<char>().swap(buffer_);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001222}
1223
Darin Petkov0406e402010-10-06 21:33:11 -07001224bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1225 string update_check_response_hash) {
1226 int64_t next_operation = kUpdateStateOperationInvalid;
1227 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1228 &next_operation) &&
1229 next_operation != kUpdateStateOperationInvalid &&
1230 next_operation > 0);
1231
1232 string interrupted_hash;
1233 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1234 &interrupted_hash) &&
David Zeuthenc41c2282013-06-17 16:33:06 -07001235 !interrupted_hash.empty() &&
1236 interrupted_hash == update_check_response_hash);
Darin Petkov0406e402010-10-06 21:33:11 -07001237
Darin Petkov61426142010-10-08 11:04:55 -07001238 int64_t resumed_update_failures;
1239 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1240 &resumed_update_failures) ||
1241 resumed_update_failures <= kMaxResumedUpdateFailures);
1242
Darin Petkov0406e402010-10-06 21:33:11 -07001243 // Sanity check the rest.
1244 int64_t next_data_offset = -1;
1245 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1246 &next_data_offset) &&
1247 next_data_offset >= 0);
1248
Darin Petkov437adc42010-10-07 13:12:24 -07001249 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001250 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001251 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1252 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001253
1254 int64_t manifest_metadata_size = 0;
1255 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1256 &manifest_metadata_size) &&
1257 manifest_metadata_size > 0);
1258
1259 return true;
1260}
1261
Darin Petkov9b230572010-10-08 10:20:09 -07001262bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001263 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1264 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001265 if (!quick) {
1266 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1267 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001268 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001269 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1270 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001271 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001272 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001273 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001274 }
Darin Petkov73058b42010-10-06 16:32:19 -07001275 return true;
1276}
1277
1278bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001279 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001280 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001281 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001282 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001283 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001284 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001285 hash_calculator_.GetContext()));
1286 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1287 buffer_offset_));
1288 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001289
1290 if (next_operation_num_ < num_total_operations_) {
1291 const bool is_kernel_partition =
1292 next_operation_num_ >= num_rootfs_operations_;
1293 const DeltaArchiveManifest_InstallOperation &op =
1294 is_kernel_partition ?
1295 manifest_.kernel_install_operations(
1296 next_operation_num_ - num_rootfs_operations_) :
1297 manifest_.install_operations(next_operation_num_);
1298 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1299 op.data_length()));
1300 } else {
1301 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1302 0));
1303 }
Darin Petkov0406e402010-10-06 21:33:11 -07001304 }
Darin Petkov73058b42010-10-06 16:32:19 -07001305 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1306 next_operation_num_));
1307 return true;
1308}
1309
Darin Petkov9b230572010-10-08 10:20:09 -07001310bool DeltaPerformer::PrimeUpdateState() {
1311 CHECK(manifest_valid_);
1312 block_size_ = manifest_.block_size();
1313
1314 int64_t next_operation = kUpdateStateOperationInvalid;
1315 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1316 next_operation == kUpdateStateOperationInvalid ||
1317 next_operation <= 0) {
1318 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001319 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001320 return true;
1321 }
1322 next_operation_num_ = next_operation;
1323
1324 // Resuming an update -- load the rest of the update state.
1325 int64_t next_data_offset = -1;
1326 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1327 &next_data_offset) &&
1328 next_data_offset >= 0);
1329 buffer_offset_ = next_data_offset;
1330
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001331 // The signed hash context and the signature blob may be empty if the
1332 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001333 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1334 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001335 string signature_blob;
1336 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1337 signatures_message_data_.assign(signature_blob.begin(),
1338 signature_blob.end());
1339 }
Darin Petkov9b230572010-10-08 10:20:09 -07001340
1341 string hash_context;
1342 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1343 &hash_context) &&
1344 hash_calculator_.SetContext(hash_context));
1345
1346 int64_t manifest_metadata_size = 0;
1347 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1348 &manifest_metadata_size) &&
1349 manifest_metadata_size > 0);
Gilad Arnoldfe133932014-01-14 12:25:50 -08001350 metadata_size_ = manifest_metadata_size;
Darin Petkov9b230572010-10-08 10:20:09 -07001351
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001352 // Advance the download progress to reflect what doesn't need to be
1353 // re-downloaded.
1354 total_bytes_received_ += buffer_offset_;
1355
Darin Petkov61426142010-10-08 11:04:55 -07001356 // Speculatively count the resume as a failure.
1357 int64_t resumed_update_failures;
1358 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1359 resumed_update_failures++;
1360 } else {
1361 resumed_update_failures = 1;
1362 }
1363 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001364 return true;
1365}
1366
David Zeuthena99981f2013-04-29 13:42:47 -07001367void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001368 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001369}
1370
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001371} // namespace chromeos_update_engine