blob: eaa65d30e6320202a9842caa118ff1deff983dd8 [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;
45
Darin Petkovabc7bc02011-02-23 14:39:43 -080046const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
47 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080048const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
49const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
50const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
51const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080052
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070053namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070054const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070055const int kMaxResumedUpdateFailures = 10;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070056// Opens path for read/write, put the fd into *fd. On success returns true
57// and sets *err to 0. On failure, returns false and sets *err to errno.
58bool OpenFile(const char* path, int* fd, int* err) {
59 if (*fd != -1) {
60 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
61 *err = EINVAL;
62 return false;
63 }
64 *fd = open(path, O_RDWR, 000);
65 if (*fd < 0) {
66 *err = errno;
67 PLOG(ERROR) << "Unable to open file " << path;
68 return false;
69 }
70 *err = 0;
71 return true;
72}
73
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070074} // namespace {}
75
Gilad Arnold8a86fa52013-01-15 12:35:05 -080076
77// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
78// arithmetic.
79static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
80 return part * norm / total;
81}
82
83void DeltaPerformer::LogProgress(const char* message_prefix) {
84 // Format operations total count and percentage.
85 string total_operations_str("?");
86 string completed_percentage_str("");
87 if (num_total_operations_) {
88 total_operations_str = StringPrintf("%zu", num_total_operations_);
89 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
90 completed_percentage_str =
91 StringPrintf(" (%llu%%)",
92 IntRatio(next_operation_num_, num_total_operations_,
93 100));
94 }
95
96 // Format download total count and percentage.
97 size_t payload_size = install_plan_->payload_size;
98 string payload_size_str("?");
99 string downloaded_percentage_str("");
100 if (payload_size) {
101 payload_size_str = StringPrintf("%zu", payload_size);
102 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
103 downloaded_percentage_str =
104 StringPrintf(" (%llu%%)",
105 IntRatio(total_bytes_received_, payload_size, 100));
106 }
107
108 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
109 << "/" << total_operations_str << " operations"
110 << completed_percentage_str << ", " << total_bytes_received_
111 << "/" << payload_size_str << " bytes downloaded"
112 << downloaded_percentage_str << ", overall progress "
113 << overall_progress_ << "%";
114}
115
116void DeltaPerformer::UpdateOverallProgress(bool force_log,
117 const char* message_prefix) {
118 // Compute our download and overall progress.
119 unsigned new_overall_progress = 0;
120 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
121 progress_weight_dont_add_up);
122 // Only consider download progress if its total size is known; otherwise
123 // adjust the operations weight to compensate for the absence of download
124 // progress. Also, make sure to cap the download portion at
125 // kProgressDownloadWeight, in case we end up downloading more than we
126 // initially expected (this indicates a problem, but could generally happen).
127 // TODO(garnold) the correction of operations weight when we do not have the
128 // total payload size, as well as the conditional guard below, should both be
129 // eliminated once we ensure that the payload_size in the install plan is
130 // always given and is non-zero. This currently isn't the case during unit
131 // tests (see chromium-os:37969).
132 size_t payload_size = install_plan_->payload_size;
133 unsigned actual_operations_weight = kProgressOperationsWeight;
134 if (payload_size)
135 new_overall_progress += min(
136 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
137 kProgressDownloadWeight)),
138 kProgressDownloadWeight);
139 else
140 actual_operations_weight += kProgressDownloadWeight;
141
142 // Only add completed operations if their total number is known; we definitely
143 // expect an update to have at least one operation, so the expectation is that
144 // this will eventually reach |actual_operations_weight|.
145 if (num_total_operations_)
146 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
147 actual_operations_weight);
148
149 // Progress ratio cannot recede, unless our assumptions about the total
150 // payload size, total number of operations, or the monotonicity of progress
151 // is breached.
152 if (new_overall_progress < overall_progress_) {
153 LOG(WARNING) << "progress counter receded from " << overall_progress_
154 << "% down to " << new_overall_progress << "%; this is a bug";
155 force_log = true;
156 }
157 overall_progress_ = new_overall_progress;
158
159 // Update chunk index, log as needed: if forced by called, or we completed a
160 // progress chunk, or a timeout has expired.
161 base::Time curr_time = base::Time::Now();
162 unsigned curr_progress_chunk =
163 overall_progress_ * kProgressLogMaxChunks / 100;
164 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
165 curr_time > forced_progress_log_time_) {
166 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
167 LogProgress(message_prefix);
168 }
169 last_progress_chunk_ = curr_progress_chunk;
170}
171
172
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700173// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
174// it safely. Returns false otherwise.
175bool DeltaPerformer::IsIdempotentOperation(
176 const DeltaArchiveManifest_InstallOperation& op) {
177 if (op.src_extents_size() == 0) {
178 return true;
179 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700180 // When in doubt, it's safe to declare an op non-idempotent. Note that we
181 // could detect other types of idempotent operations here such as a MOVE that
182 // moves blocks onto themselves. However, we rely on the server to not send
183 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700184 ExtentRanges src_ranges;
185 src_ranges.AddRepeatedExtents(op.src_extents());
186 const uint64_t block_count = src_ranges.blocks();
187 src_ranges.SubtractRepeatedExtents(op.dst_extents());
188 return block_count == src_ranges.blocks();
189}
190
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700191int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700192 int err;
193 if (OpenFile(path, &fd_, &err))
194 path_ = path;
195 return -err;
196}
197
198bool DeltaPerformer::OpenKernel(const char* kernel_path) {
199 int err;
200 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
201 if (success)
202 kernel_path_ = kernel_path;
203 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700204}
205
206int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700207 int err = 0;
208 if (close(kernel_fd_) == -1) {
209 err = errno;
210 PLOG(ERROR) << "Unable to close kernel fd:";
211 }
212 if (close(fd_) == -1) {
213 err = errno;
214 PLOG(ERROR) << "Unable to close rootfs fd:";
215 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700216 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800217 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700218 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800219 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700220 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
221 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800222 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800223 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700224 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700225}
226
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700227namespace {
228
229void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
230 string sha256;
231 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
232 info.hash().size(),
233 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800234 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
235 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700236 } else {
237 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
238 }
239}
240
241void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
242 if (manifest.has_old_kernel_info())
243 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
244 if (manifest.has_old_rootfs_info())
245 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
246 if (manifest.has_new_kernel_info())
247 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
248 if (manifest.has_new_rootfs_info())
249 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
250}
251
252} // namespace {}
253
Don Garrett4d039442013-10-28 18:40:06 -0700254uint64_t DeltaPerformer::GetVersionOffset() {
255 // Manifest size is stored right after the magic string and the version.
256 return strlen(kDeltaMagic);
257}
258
Jay Srinivasanf4318702012-09-24 11:56:24 -0700259uint64_t DeltaPerformer::GetManifestSizeOffset() {
260 // Manifest size is stored right after the magic string and the version.
261 return strlen(kDeltaMagic) + kDeltaVersionSize;
262}
263
264uint64_t DeltaPerformer::GetManifestOffset() {
265 // Actual manifest begins right after the manifest size field.
266 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
267}
268
269
Darin Petkov9574f7e2011-01-13 10:48:12 -0800270DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
271 const std::vector<char>& payload,
272 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700273 uint64_t* metadata_size,
David Zeuthena99981f2013-04-29 13:42:47 -0700274 ErrorCode* error) {
275 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700276
Jay Srinivasanf4318702012-09-24 11:56:24 -0700277 // manifest_offset is the byte offset where the manifest protobuf begins.
278 const uint64_t manifest_offset = GetManifestOffset();
279 if (payload.size() < manifest_offset) {
280 // Don't have enough bytes to even know the manifest size.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800281 return kMetadataParseInsufficientData;
282 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700283
Jay Srinivasanf4318702012-09-24 11:56:24 -0700284 // Validate the magic string.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800285 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
286 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
David Zeuthena99981f2013-04-29 13:42:47 -0700287 *error = kErrorCodeDownloadInvalidMetadataMagicString;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800288 return kMetadataParseError;
289 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700290
Don Garrett4d039442013-10-28 18:40:06 -0700291 // Extract the payload version from the metadata.
292 uint64_t major_payload_version;
293 COMPILE_ASSERT(sizeof(major_payload_version) == kDeltaVersionSize,
294 major_payload_version_size_mismatch);
295 memcpy(&major_payload_version,
296 &payload[GetVersionOffset()],
297 kDeltaVersionSize);
298 // switch big endian to host
299 major_payload_version = be64toh(major_payload_version);
300
301 if (major_payload_version != kSupportedMajorPayloadVersion) {
302 LOG(ERROR) << "Bad payload format -- unsupported payload version: "
303 << major_payload_version;
304 *error = kErrorCodeUnsupportedMajorPayloadVersion;
305 return kMetadataParseError;
306 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700307
Jay Srinivasanf4318702012-09-24 11:56:24 -0700308 // Next, parse the manifest size.
309 uint64_t manifest_size;
310 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
311 manifest_size_size_mismatch);
312 memcpy(&manifest_size,
313 &payload[GetManifestSizeOffset()],
314 kDeltaManifestSizeSize);
315 manifest_size = be64toh(manifest_size); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700316
317 // Now, check if the metasize we computed matches what was passed in
318 // through Omaha Response.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700319 *metadata_size = manifest_offset + manifest_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700320
Jay Srinivasanf4318702012-09-24 11:56:24 -0700321 // If the metadata size is present in install plan, check for it immediately
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700322 // even before waiting for that many number of bytes to be downloaded
323 // in the payload. This will prevent any attack which relies on us downloading
Jay Srinivasanf4318702012-09-24 11:56:24 -0700324 // data beyond the expected metadata size.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800325 if (install_plan_->hash_checks_mandatory) {
326 if (install_plan_->metadata_size != *metadata_size) {
327 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
328 << install_plan_->metadata_size << ") is missing/incorrect."
329 << ", Actual = " << *metadata_size;
David Zeuthena99981f2013-04-29 13:42:47 -0700330 *error = kErrorCodeDownloadInvalidMetadataSize;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800331 return kMetadataParseError;
332 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700333 }
334
335 // Now that we have validated the metadata size, we should wait for the full
336 // metadata to be read in before we can parse it.
337 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800338 return kMetadataParseInsufficientData;
339 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700340
341 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700342 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700343 // that we just log once (instead of logging n times) if it takes n
344 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800345 if (install_plan_->metadata_size == *metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700346 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800347 } else {
348 // For mandatory-cases, we'd have already returned a kMetadataParseError
349 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
350 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
351 << install_plan_->metadata_size
352 << ") in Omaha response as validation is not mandatory. "
353 << "Trusting metadata size in payload = " << *metadata_size;
David Zeuthena99981f2013-04-29 13:42:47 -0700354 SendUmaStat(kErrorCodeDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800355 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700356
Jay Srinivasanf4318702012-09-24 11:56:24 -0700357 // We have the full metadata in |payload|. Verify its integrity
358 // and authenticity based on the information we have in Omaha response.
359 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
David Zeuthena99981f2013-04-29 13:42:47 -0700360 if (*error != kErrorCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800361 if (install_plan_->hash_checks_mandatory) {
David Zeuthenbc27aac2013-11-26 11:17:48 -0800362 // The autoupdate_CatchBadSignatures test checks for this string
363 // in log-files. Keep in sync.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800364 LOG(ERROR) << "Mandatory metadata signature validation failed";
365 return kMetadataParseError;
366 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700367
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800368 // For non-mandatory cases, just send a UMA stat.
369 LOG(WARNING) << "Ignoring metadata signature validation failures";
370 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700371 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700372 }
373
Jay Srinivasanf4318702012-09-24 11:56:24 -0700374 // The metadata in |payload| is deemed valid. So, it's now safe to
375 // parse the protobuf.
376 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800377 LOG(ERROR) << "Unable to parse manifest in update file.";
David Zeuthena99981f2013-04-29 13:42:47 -0700378 *error = kErrorCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800379 return kMetadataParseError;
380 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800381 return kMetadataParseSuccess;
382}
383
384
Don Garrette410e0f2011-11-10 15:39:01 -0800385// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800386// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700387// and stores an action exit code in |error|.
388bool DeltaPerformer::Write(const void* bytes, size_t count,
David Zeuthena99981f2013-04-29 13:42:47 -0700389 ErrorCode *error) {
390 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700391
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700392 const char* c_bytes = reinterpret_cast<const char*>(bytes);
393 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800394 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800395
396 // Update the total byte downloaded count and the progress logs.
397 total_bytes_received_ += count;
398 UpdateOverallProgress(false, "Completed ");
399
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700400 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800401 MetadataParseResult result = ParsePayloadMetadata(buffer_,
402 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700403 &manifest_metadata_size_,
404 error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700405 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800406 return false;
Gilad Arnold5cac5912013-05-24 17:21:17 -0700407 if (result == kMetadataParseInsufficientData)
Don Garrette410e0f2011-11-10 15:39:01 -0800408 return true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700409
410 // Checks the integrity of the payload manifest.
411 if ((*error = ValidateManifest()) != kErrorCodeSuccess)
412 return false;
413
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700414 // Remove protobuf and header info from buffer_, so buffer_ contains
415 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700416 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700417 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700418 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700419 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700420 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700421
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700422 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700423 if (!PrimeUpdateState()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700424 *error = kErrorCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700425 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800426 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700427 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800428
429 num_rootfs_operations_ = manifest_.install_operations_size();
430 num_total_operations_ =
431 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
432 if (next_operation_num_ > 0)
433 UpdateOverallProgress(true, "Resuming after ");
434 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700435 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800436
437 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700438 // Check if we should cancel the current attempt for any reason.
439 // In this case, *error will have already been populated with the reason
440 // why we're cancelling.
441 if (system_state_->update_attempter()->ShouldCancel(error))
442 return false;
443
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800444 const bool is_kernel_partition =
445 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700446 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800447 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700448 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800449 next_operation_num_ - num_rootfs_operations_) :
450 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700451 if (!CanPerformInstallOperation(op)) {
452 // This means we don't have enough bytes received yet to carry out the
453 // next operation.
454 return true;
455 }
456
Jay Srinivasanf4318702012-09-24 11:56:24 -0700457 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700458 // Otherwise, keep the old behavior. This serves as a knob to disable
459 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800460 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
461 // we would have already failed in ParsePayloadMetadata method and thus not
462 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700463 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700464 // Note: Validate must be called only if CanPerformInstallOperation is
465 // called. Otherwise, we might be failing operations before even if there
466 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800467 *error = ValidateOperationHash(op);
David Zeuthena99981f2013-04-29 13:42:47 -0700468 if (*error != kErrorCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800469 if (install_plan_->hash_checks_mandatory) {
470 LOG(ERROR) << "Mandatory operation hash check failed";
471 return false;
472 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700473
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800474 // For non-mandatory cases, just send a UMA stat.
475 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700476 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700477 *error = kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700478 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700479 }
480
Darin Petkov45580e42010-10-08 14:02:40 -0700481 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700482 ScopedTerminatorExitUnblocker exit_unblocker =
483 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700484 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700485 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
486 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700487 if (!PerformReplaceOperation(op, is_kernel_partition)) {
488 LOG(ERROR) << "Failed to perform replace operation "
489 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700490 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800491 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700492 }
493 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700494 if (!PerformMoveOperation(op, is_kernel_partition)) {
495 LOG(ERROR) << "Failed to perform move operation "
496 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700497 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800498 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700499 }
500 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700501 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
502 LOG(ERROR) << "Failed to perform bsdiff operation "
503 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700504 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800505 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700506 }
507 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800508
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700509 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800510 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700511 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700512 }
Don Garrette410e0f2011-11-10 15:39:01 -0800513 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700514}
515
David Zeuthen8f191b22013-08-06 12:27:50 -0700516bool DeltaPerformer::IsManifestValid() {
517 return manifest_valid_;
518}
519
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700520bool DeltaPerformer::CanPerformInstallOperation(
521 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
522 operation) {
523 // Move operations don't require any data blob, so they can always
524 // be performed
525 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
526 return true;
527
528 // See if we have the entire data blob in the buffer
529 if (operation.data_offset() < buffer_offset_) {
530 LOG(ERROR) << "we threw away data it seems?";
531 return false;
532 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700533
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700534 return (operation.data_offset() + operation.data_length()) <=
535 (buffer_offset_ + buffer_.size());
536}
537
538bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700539 const DeltaArchiveManifest_InstallOperation& operation,
540 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700541 CHECK(operation.type() == \
542 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
543 operation.type() == \
544 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
545
546 // Since we delete data off the beginning of the buffer as we use it,
547 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700548 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
549 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700550
Darin Petkov437adc42010-10-07 13:12:24 -0700551 // Extract the signature message if it's in this operation.
552 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700553
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700554 DirectExtentWriter direct_writer;
555 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
556 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700557
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700558 // Since bzip decompression is optional, we have a variable writer that will
559 // point to one of the ExtentWriter objects above.
560 ExtentWriter* writer = NULL;
561 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
562 writer = &zero_pad_writer;
563 } else if (operation.type() ==
564 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
565 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
566 writer = bzip_writer.get();
567 } else {
568 NOTREACHED();
569 }
570
571 // Create a vector of extents to pass to the ExtentWriter.
572 vector<Extent> extents;
573 for (int i = 0; i < operation.dst_extents_size(); i++) {
574 extents.push_back(operation.dst_extents(i));
575 }
576
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700577 int fd = is_kernel_partition ? kernel_fd_ : fd_;
578
579 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700580 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
581 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700582
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700583 // Update buffer
584 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700585 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700586 return true;
587}
588
589bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700590 const DeltaArchiveManifest_InstallOperation& operation,
591 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700592 // Calculate buffer size. Note, this function doesn't do a sliding
593 // window to copy in case the source and destination blocks overlap.
594 // If we wanted to do a sliding window, we could program the server
595 // to generate deltas that effectively did a sliding window.
596
597 uint64_t blocks_to_read = 0;
598 for (int i = 0; i < operation.src_extents_size(); i++)
599 blocks_to_read += operation.src_extents(i).num_blocks();
600
601 uint64_t blocks_to_write = 0;
602 for (int i = 0; i < operation.dst_extents_size(); i++)
603 blocks_to_write += operation.dst_extents(i).num_blocks();
604
605 DCHECK_EQ(blocks_to_write, blocks_to_read);
606 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700607
608 int fd = is_kernel_partition ? kernel_fd_ : fd_;
609
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700610 // Read in bytes.
611 ssize_t bytes_read = 0;
612 for (int i = 0; i < operation.src_extents_size(); i++) {
613 ssize_t bytes_read_this_iteration = 0;
614 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200615 const size_t bytes = extent.num_blocks() * block_size_;
616 if (extent.start_block() == kSparseHole) {
617 bytes_read_this_iteration = bytes;
618 memset(&buf[bytes_read], 0, bytes);
619 } else {
620 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
621 &buf[bytes_read],
622 bytes,
623 extent.start_block() * block_size_,
624 &bytes_read_this_iteration));
625 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700626 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200627 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700628 bytes_read += bytes_read_this_iteration;
629 }
630
Darin Petkov45580e42010-10-08 14:02:40 -0700631 // If this is a non-idempotent operation, request a delayed exit and clear the
632 // update state in case the operation gets interrupted. Do this as late as
633 // possible.
634 if (!IsIdempotentOperation(operation)) {
635 Terminator::set_exit_blocked(true);
636 ResetUpdateProgress(prefs_, true);
637 }
638
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700639 // Write bytes out.
640 ssize_t bytes_written = 0;
641 for (int i = 0; i < operation.dst_extents_size(); i++) {
642 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200643 const size_t bytes = extent.num_blocks() * block_size_;
644 if (extent.start_block() == kSparseHole) {
Darin Petkov741a8222013-05-02 10:02:34 +0200645 DCHECK(buf.begin() + bytes_written ==
646 std::search_n(buf.begin() + bytes_written,
647 buf.begin() + bytes_written + bytes,
648 bytes, 0));
Darin Petkov8a075a72013-04-25 14:46:09 +0200649 } else {
650 TEST_AND_RETURN_FALSE(
651 utils::PWriteAll(fd,
652 &buf[bytes_written],
653 bytes,
654 extent.start_block() * block_size_));
655 }
656 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700657 }
658 DCHECK_EQ(bytes_written, bytes_read);
659 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
660 return true;
661}
662
663bool DeltaPerformer::ExtentsToBsdiffPositionsString(
664 const RepeatedPtrField<Extent>& extents,
665 uint64_t block_size,
666 uint64_t full_length,
667 string* positions_string) {
668 string ret;
669 uint64_t length = 0;
670 for (int i = 0; i < extents.size(); i++) {
671 Extent extent = extents.Get(i);
672 int64_t start = extent.start_block();
673 uint64_t this_length = min(full_length - length,
674 extent.num_blocks() * block_size);
675 if (start == static_cast<int64_t>(kSparseHole))
676 start = -1;
677 else
678 start *= block_size;
679 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
680 length += this_length;
681 }
682 TEST_AND_RETURN_FALSE(length == full_length);
683 if (!ret.empty())
684 ret.resize(ret.size() - 1); // Strip trailing comma off
685 *positions_string = ret;
686 return true;
687}
688
689bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700690 const DeltaArchiveManifest_InstallOperation& operation,
691 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700692 // Since we delete data off the beginning of the buffer as we use it,
693 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700694 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
695 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700696
697 string input_positions;
698 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
699 block_size_,
700 operation.src_length(),
701 &input_positions));
702 string output_positions;
703 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
704 block_size_,
705 operation.dst_length(),
706 &output_positions));
707
708 string temp_filename;
709 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
710 &temp_filename,
711 NULL));
712 ScopedPathUnlinker path_unlinker(temp_filename);
713 {
714 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
715 ScopedFdCloser fd_closer(&fd);
716 TEST_AND_RETURN_FALSE(
717 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
718 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700719
Darin Petkov7f2ec752013-04-03 14:45:19 +0200720 // Update the buffer to release the patch data memory as soon as the patch
721 // file is written out.
722 buffer_offset_ += operation.data_length();
723 DiscardBufferHeadBytes(operation.data_length());
724
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700725 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Darin Petkov3d1670d2013-07-12 14:37:06 +0200726 const string path = StringPrintf("/proc/self/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700727
Darin Petkov45580e42010-10-08 14:02:40 -0700728 // If this is a non-idempotent operation, request a delayed exit and clear the
729 // update state in case the operation gets interrupted. Do this as late as
730 // possible.
731 if (!IsIdempotentOperation(operation)) {
732 Terminator::set_exit_blocked(true);
733 ResetUpdateProgress(prefs_, true);
734 }
735
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700736 vector<string> cmd;
737 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700738 cmd.push_back(path);
739 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700740 cmd.push_back(temp_filename);
741 cmd.push_back(input_positions);
742 cmd.push_back(output_positions);
743 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700744 TEST_AND_RETURN_FALSE(
745 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700746 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700747 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700748 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700749 TEST_AND_RETURN_FALSE(return_code == 0);
750
751 if (operation.dst_length() % block_size_) {
752 // Zero out rest of final block.
753 // TODO(adlr): build this into bspatch; it's more efficient that way.
754 const Extent& last_extent =
755 operation.dst_extents(operation.dst_extents_size() - 1);
756 const uint64_t end_byte =
757 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
758 const uint64_t begin_byte =
759 end_byte - (block_size_ - operation.dst_length() % block_size_);
760 vector<char> zeros(end_byte - begin_byte);
761 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700762 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700763 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700764 return true;
765}
766
Darin Petkovd7061ab2010-10-06 14:37:09 -0700767bool DeltaPerformer::ExtractSignatureMessage(
768 const DeltaArchiveManifest_InstallOperation& operation) {
769 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
770 !manifest_.has_signatures_offset() ||
771 manifest_.signatures_offset() != operation.data_offset()) {
772 return false;
773 }
774 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
775 manifest_.signatures_size() == operation.data_length());
776 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
777 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
778 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700779 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700780 buffer_.begin(),
781 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700782
783 // Save the signature blob because if the update is interrupted after the
784 // download phase we don't go through this path anymore. Some alternatives to
785 // consider:
786 //
787 // 1. On resume, re-download the signature blob from the server and re-verify
788 // it.
789 //
790 // 2. Verify the signature as soon as it's received and don't checkpoint the
791 // blob and the signed sha-256 context.
792 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
793 string(&signatures_message_data_[0],
794 signatures_message_data_.size())))
795 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700796 // The hash of all data consumed so far should be verified against the signed
797 // hash.
798 signed_hash_context_ = hash_calculator_.GetContext();
799 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
800 signed_hash_context_))
801 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700802 LOG(INFO) << "Extracted signature data of size "
803 << manifest_.signatures_size() << " at "
804 << manifest_.signatures_offset();
805 return true;
806}
807
David Zeuthene7f89172013-10-31 10:21:04 -0700808bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
809 if (system_state_->hardware()->IsOfficialBuild() ||
810 utils::FileExists(public_key_path_.c_str()) ||
811 install_plan_->public_key_rsa.empty())
812 return false;
813
814 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
815 out_tmp_key))
816 return false;
817
818 return true;
819}
820
David Zeuthena99981f2013-04-29 13:42:47 -0700821ErrorCode DeltaPerformer::ValidateMetadataSignature(
Jay Srinivasanf4318702012-09-24 11:56:24 -0700822 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700823
Jay Srinivasanf4318702012-09-24 11:56:24 -0700824 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800825 if (install_plan_->hash_checks_mandatory) {
826 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700827 return kErrorCodeDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800828 }
829
830 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700831 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
David Zeuthena99981f2013-04-29 13:42:47 -0700832 SendUmaStat(kErrorCodeDownloadMetadataSignatureMissingError);
833 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700834 }
835
836 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700837 vector<char> metadata_signature;
838 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
839 &metadata_signature)) {
840 LOG(ERROR) << "Unable to decode base64 metadata signature: "
841 << install_plan_->metadata_signature;
David Zeuthena99981f2013-04-29 13:42:47 -0700842 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700843 }
844
David Zeuthene7f89172013-10-31 10:21:04 -0700845 // See if we should use the public RSA key in the Omaha response.
846 base::FilePath path_to_public_key(public_key_path_);
847 base::FilePath tmp_key;
848 if (GetPublicKeyFromResponse(&tmp_key))
849 path_to_public_key = tmp_key;
850 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
851 if (tmp_key.empty())
852 tmp_key_remover.set_should_remove(false);
853
854 LOG(INFO) << "Verifying metadata hash signature using public key: "
855 << path_to_public_key.value();
856
Jay Srinivasanf4318702012-09-24 11:56:24 -0700857 vector<char> expected_metadata_hash;
858 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
David Zeuthene7f89172013-10-31 10:21:04 -0700859 path_to_public_key.value(),
Jay Srinivasanf4318702012-09-24 11:56:24 -0700860 &expected_metadata_hash)) {
861 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
David Zeuthena99981f2013-04-29 13:42:47 -0700862 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700863 }
864
Jay Srinivasanf4318702012-09-24 11:56:24 -0700865 OmahaHashCalculator metadata_hasher;
866 metadata_hasher.Update(metadata, metadata_size);
867 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700868 LOG(ERROR) << "Unable to compute actual hash of manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700869 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700870 }
871
Jay Srinivasanf4318702012-09-24 11:56:24 -0700872 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
873 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
874 if (calculated_metadata_hash.empty()) {
875 LOG(ERROR) << "Computed actual hash of metadata is empty.";
David Zeuthena99981f2013-04-29 13:42:47 -0700876 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700877 }
878
Jay Srinivasanf4318702012-09-24 11:56:24 -0700879 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700880 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700881 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700882 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700883 utils::HexDumpVector(calculated_metadata_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700884 return kErrorCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700885 }
886
David Zeuthenbc27aac2013-11-26 11:17:48 -0800887 // The autoupdate_CatchBadSignatures test checks for this string in
888 // log-files. Keep in sync.
David Zeuthene7f89172013-10-31 10:21:04 -0700889 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
David Zeuthena99981f2013-04-29 13:42:47 -0700890 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700891}
892
Gilad Arnold21504f02013-05-24 08:51:22 -0700893ErrorCode DeltaPerformer::ValidateManifest() {
894 // Ensure that a full update does not contain old partition hashes, which is
895 // indicative of a delta.
896 //
897 // TODO(garnold) in general, the presence of an old partition hash should be
898 // the sole indicator for a delta update, as we would generally like update
899 // payloads to be self contained and not assume an Omaha response to tell us
900 // that. However, since this requires some massive reengineering of the update
901 // flow (making filesystem copying happen conditionally only *after*
902 // downloading and parsing of the update manifest) we'll put it off for now.
903 // See chromium-os:7597 for further discussion.
904 if (install_plan_->is_full_update &&
905 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info())) {
906 LOG(ERROR) << "Purported full payload contains old partition "
907 "hash(es), aborting update";
908 return kErrorCodePayloadMismatchedType;
909 }
910
911 // TODO(garnold) we should be adding more and more manifest checks, such as
912 // partition boundaries etc (see chromium-os:37661).
913
914 return kErrorCodeSuccess;
915}
916
David Zeuthena99981f2013-04-29 13:42:47 -0700917ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800918 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700919
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700920 if (!operation.data_sha256_hash().size()) {
921 if (!operation.data_length()) {
922 // Operations that do not have any data blob won't have any operation hash
923 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700924 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800925 // has already been validated. This is true for both HTTP and HTTPS cases.
David Zeuthena99981f2013-04-29 13:42:47 -0700926 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700927 }
928
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800929 // No hash is present for an operation that has data blobs. This shouldn't
930 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700931 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800932 // hashes. So if it happens it means either we've turned operation hash
933 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700934 // One caveat though: The last operation is a dummy signature operation
935 // that doesn't have a hash at the time the manifest is created. So we
936 // should not complaint about that operation. This operation can be
937 // recognized by the fact that it's offset is mentioned in the manifest.
938 if (manifest_.signatures_offset() &&
939 manifest_.signatures_offset() == operation.data_offset()) {
940 LOG(INFO) << "Skipping hash verification for signature operation "
941 << next_operation_num_ + 1;
942 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800943 if (install_plan_->hash_checks_mandatory) {
944 LOG(ERROR) << "Missing mandatory operation hash for operation "
945 << next_operation_num_ + 1;
David Zeuthena99981f2013-04-29 13:42:47 -0700946 return kErrorCodeDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800947 }
948
949 // For non-mandatory cases, just send a UMA stat.
950 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
951 << " as there's no operation hash in manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700952 SendUmaStat(kErrorCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700953 }
David Zeuthena99981f2013-04-29 13:42:47 -0700954 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700955 }
956
957 vector<char> expected_op_hash;
958 expected_op_hash.assign(operation.data_sha256_hash().data(),
959 (operation.data_sha256_hash().data() +
960 operation.data_sha256_hash().size()));
961
962 OmahaHashCalculator operation_hasher;
963 operation_hasher.Update(&buffer_[0], operation.data_length());
964 if (!operation_hasher.Finalize()) {
965 LOG(ERROR) << "Unable to compute actual hash of operation "
966 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700967 return kErrorCodeDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700968 }
969
970 vector<char> calculated_op_hash = operation_hasher.raw_hash();
971 if (calculated_op_hash != expected_op_hash) {
972 LOG(ERROR) << "Hash verification failed for operation "
973 << next_operation_num_ << ". Expected hash = ";
974 utils::HexDumpVector(expected_op_hash);
975 LOG(ERROR) << "Calculated hash over " << operation.data_length()
976 << " bytes at offset: " << operation.data_offset() << " = ";
977 utils::HexDumpVector(calculated_op_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700978 return kErrorCodeDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700979 }
980
David Zeuthena99981f2013-04-29 13:42:47 -0700981 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700982}
983
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700984#define TEST_AND_RETURN_VAL(_retval, _condition) \
985 do { \
986 if (!(_condition)) { \
987 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
988 return _retval; \
989 } \
990 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700991
David Zeuthena99981f2013-04-29 13:42:47 -0700992ErrorCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700993 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700994 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -0700995
996 // See if we should use the public RSA key in the Omaha response.
997 base::FilePath path_to_public_key(public_key_path_);
998 base::FilePath tmp_key;
999 if (GetPublicKeyFromResponse(&tmp_key))
1000 path_to_public_key = tmp_key;
1001 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
1002 if (tmp_key.empty())
1003 tmp_key_remover.set_should_remove(false);
1004
1005 LOG(INFO) << "Verifying payload using public key: "
1006 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001007
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001008 // Verifies the download size.
David Zeuthena99981f2013-04-29 13:42:47 -07001009 TEST_AND_RETURN_VAL(kErrorCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001010 update_check_response_size ==
1011 manifest_metadata_size_ + buffer_offset_);
1012
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001013 // Verifies the payload hash.
1014 const string& payload_hash_data = hash_calculator_.hash();
David Zeuthena99981f2013-04-29 13:42:47 -07001015 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001016 !payload_hash_data.empty());
David Zeuthena99981f2013-04-29 13:42:47 -07001017 TEST_AND_RETURN_VAL(kErrorCodePayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001018 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001019
Darin Petkov437adc42010-10-07 13:12:24 -07001020 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001021 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001022 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
David Zeuthena99981f2013-04-29 13:42:47 -07001023 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001024 }
David Zeuthena99981f2013-04-29 13:42:47 -07001025 TEST_AND_RETURN_VAL(kErrorCodeSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001026 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -07001027 vector<char> signed_hash_data;
David Zeuthena99981f2013-04-29 13:42:47 -07001028 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001029 PayloadSigner::VerifySignature(
1030 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001031 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001032 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001033 OmahaHashCalculator signed_hasher;
David Zeuthena99981f2013-04-29 13:42:47 -07001034 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001035 signed_hasher.SetContext(signed_hash_context_));
David Zeuthena99981f2013-04-29 13:42:47 -07001036 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001037 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -07001038 vector<char> hash_data = signed_hasher.raw_hash();
1039 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -07001040 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001041 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001042 if (hash_data != signed_hash_data) {
David Zeuthenbc27aac2013-11-26 11:17:48 -08001043 // The autoupdate_CatchBadSignatures test checks for this string
1044 // in log-files. Keep in sync.
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001045 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001046 "Attached Signature:";
1047 utils::HexDumpVector(signed_hash_data);
1048 LOG(ERROR) << "Computed Signature:";
1049 utils::HexDumpVector(hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -07001050 return kErrorCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001051 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001052
David Zeuthene7f89172013-10-31 10:21:04 -07001053 LOG(INFO) << "Payload hash matches value in payload.";
1054
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001055 // At this point, we are guaranteed to have downloaded a full payload, i.e
1056 // the one whose size matches the size mentioned in Omaha response. If any
1057 // errors happen after this, it's likely a problem with the payload itself or
1058 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001059 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001060 system_state_->payload_state()->DownloadComplete();
1061
David Zeuthena99981f2013-04-29 13:42:47 -07001062 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001063}
1064
Darin Petkov3aefa862010-12-07 14:45:00 -08001065bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
1066 vector<char>* kernel_hash,
1067 uint64_t* rootfs_size,
1068 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001069 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1070 manifest_.has_new_kernel_info() &&
1071 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001072 *kernel_size = manifest_.new_kernel_info().size();
1073 *rootfs_size = manifest_.new_rootfs_info().size();
1074 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1075 manifest_.new_kernel_info().hash().end());
1076 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1077 manifest_.new_rootfs_info().hash().end());
1078 kernel_hash->swap(new_kernel_hash);
1079 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001080 return true;
1081}
1082
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001083namespace {
1084void LogVerifyError(bool is_kern,
1085 const string& local_hash,
1086 const string& expected_hash) {
1087 const char* type = is_kern ? "kernel" : "rootfs";
1088 LOG(ERROR) << "This is a server-side error due to "
1089 << "mismatched delta update image!";
1090 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1091 << "update that must be applied over a " << type << " with "
1092 << "a specific checksum, but the " << type << " we're starting "
1093 << "with doesn't have that checksum! This means that "
1094 << "the delta I've been given doesn't match my existing "
1095 << "system. The " << type << " partition I have has hash: "
1096 << local_hash << " but the update expected me to have "
1097 << expected_hash << " .";
1098 if (is_kern) {
1099 LOG(INFO) << "To get the checksum of a kernel partition on a "
1100 << "booted machine, run this command (change /dev/sda2 "
1101 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1102 << "openssl dgst -sha256 -binary | openssl base64";
1103 } else {
1104 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1105 << "booted machine, run this command (change /dev/sda3 "
1106 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1107 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1108 << "| sed 's/[^0-9]*//') / 256 )) | "
1109 << "openssl dgst -sha256 -binary | openssl base64";
1110 }
1111 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1112 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1113}
1114
1115string StringForHashBytes(const void* bytes, size_t size) {
1116 string ret;
1117 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1118 ret = "<unknown>";
1119 }
1120 return ret;
1121}
1122} // namespace
1123
Darin Petkov698d0412010-10-13 10:59:44 -07001124bool DeltaPerformer::VerifySourcePartitions() {
1125 LOG(INFO) << "Verifying source partitions.";
1126 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001127 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001128 if (manifest_.has_old_kernel_info()) {
1129 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001130 bool valid =
1131 !install_plan_->kernel_hash.empty() &&
1132 install_plan_->kernel_hash.size() == info.hash().size() &&
1133 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001134 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001135 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001136 if (!valid) {
1137 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001138 StringForHashBytes(install_plan_->kernel_hash.data(),
1139 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001140 StringForHashBytes(info.hash().data(),
1141 info.hash().size()));
1142 }
1143 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001144 }
1145 if (manifest_.has_old_rootfs_info()) {
1146 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001147 bool valid =
1148 !install_plan_->rootfs_hash.empty() &&
1149 install_plan_->rootfs_hash.size() == info.hash().size() &&
1150 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001151 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001152 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001153 if (!valid) {
1154 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001155 StringForHashBytes(install_plan_->rootfs_hash.data(),
1156 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001157 StringForHashBytes(info.hash().data(),
1158 info.hash().size()));
1159 }
1160 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001161 }
1162 return true;
1163}
1164
Darin Petkov437adc42010-10-07 13:12:24 -07001165void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1166 hash_calculator_.Update(&buffer_[0], count);
Darin Petkov7f2ec752013-04-03 14:45:19 +02001167 // Copy the remainder data into a temporary vector first to ensure that any
1168 // unused memory in the updated |buffer_| will be released.
1169 vector<char> temp(buffer_.begin() + count, buffer_.end());
1170 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001171}
1172
Darin Petkov0406e402010-10-06 21:33:11 -07001173bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1174 string update_check_response_hash) {
1175 int64_t next_operation = kUpdateStateOperationInvalid;
1176 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1177 &next_operation) &&
1178 next_operation != kUpdateStateOperationInvalid &&
1179 next_operation > 0);
1180
1181 string interrupted_hash;
1182 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1183 &interrupted_hash) &&
David Zeuthenc41c2282013-06-17 16:33:06 -07001184 !interrupted_hash.empty() &&
1185 interrupted_hash == update_check_response_hash);
Darin Petkov0406e402010-10-06 21:33:11 -07001186
Darin Petkov61426142010-10-08 11:04:55 -07001187 int64_t resumed_update_failures;
1188 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1189 &resumed_update_failures) ||
1190 resumed_update_failures <= kMaxResumedUpdateFailures);
1191
Darin Petkov0406e402010-10-06 21:33:11 -07001192 // Sanity check the rest.
1193 int64_t next_data_offset = -1;
1194 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1195 &next_data_offset) &&
1196 next_data_offset >= 0);
1197
Darin Petkov437adc42010-10-07 13:12:24 -07001198 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001199 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001200 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1201 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001202
1203 int64_t manifest_metadata_size = 0;
1204 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1205 &manifest_metadata_size) &&
1206 manifest_metadata_size > 0);
1207
1208 return true;
1209}
1210
Darin Petkov9b230572010-10-08 10:20:09 -07001211bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001212 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1213 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001214 if (!quick) {
1215 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1216 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001217 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001218 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1219 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001220 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001221 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001222 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001223 }
Darin Petkov73058b42010-10-06 16:32:19 -07001224 return true;
1225}
1226
1227bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001228 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001229 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001230 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001231 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001232 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001233 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001234 hash_calculator_.GetContext()));
1235 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1236 buffer_offset_));
1237 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001238
1239 if (next_operation_num_ < num_total_operations_) {
1240 const bool is_kernel_partition =
1241 next_operation_num_ >= num_rootfs_operations_;
1242 const DeltaArchiveManifest_InstallOperation &op =
1243 is_kernel_partition ?
1244 manifest_.kernel_install_operations(
1245 next_operation_num_ - num_rootfs_operations_) :
1246 manifest_.install_operations(next_operation_num_);
1247 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1248 op.data_length()));
1249 } else {
1250 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1251 0));
1252 }
Darin Petkov0406e402010-10-06 21:33:11 -07001253 }
Darin Petkov73058b42010-10-06 16:32:19 -07001254 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1255 next_operation_num_));
1256 return true;
1257}
1258
Darin Petkov9b230572010-10-08 10:20:09 -07001259bool DeltaPerformer::PrimeUpdateState() {
1260 CHECK(manifest_valid_);
1261 block_size_ = manifest_.block_size();
1262
1263 int64_t next_operation = kUpdateStateOperationInvalid;
1264 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1265 next_operation == kUpdateStateOperationInvalid ||
1266 next_operation <= 0) {
1267 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001268 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001269 return true;
1270 }
1271 next_operation_num_ = next_operation;
1272
1273 // Resuming an update -- load the rest of the update state.
1274 int64_t next_data_offset = -1;
1275 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1276 &next_data_offset) &&
1277 next_data_offset >= 0);
1278 buffer_offset_ = next_data_offset;
1279
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001280 // The signed hash context and the signature blob may be empty if the
1281 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001282 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1283 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001284 string signature_blob;
1285 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1286 signatures_message_data_.assign(signature_blob.begin(),
1287 signature_blob.end());
1288 }
Darin Petkov9b230572010-10-08 10:20:09 -07001289
1290 string hash_context;
1291 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1292 &hash_context) &&
1293 hash_calculator_.SetContext(hash_context));
1294
1295 int64_t manifest_metadata_size = 0;
1296 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1297 &manifest_metadata_size) &&
1298 manifest_metadata_size > 0);
1299 manifest_metadata_size_ = manifest_metadata_size;
1300
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001301 // Advance the download progress to reflect what doesn't need to be
1302 // re-downloaded.
1303 total_bytes_received_ += buffer_offset_;
1304
Darin Petkov61426142010-10-08 11:04:55 -07001305 // Speculatively count the resume as a failure.
1306 int64_t resumed_update_failures;
1307 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1308 resumed_update_failures++;
1309 } else {
1310 resumed_update_failures = 1;
1311 }
1312 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001313 return true;
1314}
1315
David Zeuthena99981f2013-04-29 13:42:47 -07001316void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001317 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001318}
1319
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001320} // namespace chromeos_update_engine