blob: 15f9002845d77ae5f6ac6c0185b4cce9223c4f5c [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) {
362 LOG(ERROR) << "Mandatory metadata signature validation failed";
363 return kMetadataParseError;
364 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700365
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800366 // For non-mandatory cases, just send a UMA stat.
367 LOG(WARNING) << "Ignoring metadata signature validation failures";
368 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700369 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700370 }
371
Jay Srinivasanf4318702012-09-24 11:56:24 -0700372 // The metadata in |payload| is deemed valid. So, it's now safe to
373 // parse the protobuf.
374 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800375 LOG(ERROR) << "Unable to parse manifest in update file.";
David Zeuthena99981f2013-04-29 13:42:47 -0700376 *error = kErrorCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800377 return kMetadataParseError;
378 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800379 return kMetadataParseSuccess;
380}
381
382
Don Garrette410e0f2011-11-10 15:39:01 -0800383// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800384// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700385// and stores an action exit code in |error|.
386bool DeltaPerformer::Write(const void* bytes, size_t count,
David Zeuthena99981f2013-04-29 13:42:47 -0700387 ErrorCode *error) {
388 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700389
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700390 const char* c_bytes = reinterpret_cast<const char*>(bytes);
391 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800392 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800393
394 // Update the total byte downloaded count and the progress logs.
395 total_bytes_received_ += count;
396 UpdateOverallProgress(false, "Completed ");
397
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700398 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800399 MetadataParseResult result = ParsePayloadMetadata(buffer_,
400 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700401 &manifest_metadata_size_,
402 error);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700403 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800404 return false;
Gilad Arnold5cac5912013-05-24 17:21:17 -0700405 if (result == kMetadataParseInsufficientData)
Don Garrette410e0f2011-11-10 15:39:01 -0800406 return true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700407
408 // Checks the integrity of the payload manifest.
409 if ((*error = ValidateManifest()) != kErrorCodeSuccess)
410 return false;
411
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700412 // Remove protobuf and header info from buffer_, so buffer_ contains
413 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700414 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700415 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700416 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700417 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700418 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700419
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700420 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700421 if (!PrimeUpdateState()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700422 *error = kErrorCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700423 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800424 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700425 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800426
427 num_rootfs_operations_ = manifest_.install_operations_size();
428 num_total_operations_ =
429 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
430 if (next_operation_num_ > 0)
431 UpdateOverallProgress(true, "Resuming after ");
432 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700433 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800434
435 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700436 // Check if we should cancel the current attempt for any reason.
437 // In this case, *error will have already been populated with the reason
438 // why we're cancelling.
439 if (system_state_->update_attempter()->ShouldCancel(error))
440 return false;
441
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800442 const bool is_kernel_partition =
443 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700444 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800445 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700446 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800447 next_operation_num_ - num_rootfs_operations_) :
448 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700449 if (!CanPerformInstallOperation(op)) {
450 // This means we don't have enough bytes received yet to carry out the
451 // next operation.
452 return true;
453 }
454
Jay Srinivasanf4318702012-09-24 11:56:24 -0700455 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700456 // Otherwise, keep the old behavior. This serves as a knob to disable
457 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800458 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
459 // we would have already failed in ParsePayloadMetadata method and thus not
460 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700461 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700462 // Note: Validate must be called only if CanPerformInstallOperation is
463 // called. Otherwise, we might be failing operations before even if there
464 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800465 *error = ValidateOperationHash(op);
David Zeuthena99981f2013-04-29 13:42:47 -0700466 if (*error != kErrorCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800467 if (install_plan_->hash_checks_mandatory) {
468 LOG(ERROR) << "Mandatory operation hash check failed";
469 return false;
470 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700471
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800472 // For non-mandatory cases, just send a UMA stat.
473 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700474 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700475 *error = kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700476 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700477 }
478
Darin Petkov45580e42010-10-08 14:02:40 -0700479 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700480 ScopedTerminatorExitUnblocker exit_unblocker =
481 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700482 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700483 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
484 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700485 if (!PerformReplaceOperation(op, is_kernel_partition)) {
486 LOG(ERROR) << "Failed to perform replace operation "
487 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700488 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800489 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700490 }
491 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700492 if (!PerformMoveOperation(op, is_kernel_partition)) {
493 LOG(ERROR) << "Failed to perform move operation "
494 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700495 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800496 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700497 }
498 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700499 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
500 LOG(ERROR) << "Failed to perform bsdiff operation "
501 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700502 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800503 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700504 }
505 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800506
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700507 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800508 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700509 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700510 }
Don Garrette410e0f2011-11-10 15:39:01 -0800511 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700512}
513
David Zeuthen8f191b22013-08-06 12:27:50 -0700514bool DeltaPerformer::IsManifestValid() {
515 return manifest_valid_;
516}
517
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700518bool DeltaPerformer::CanPerformInstallOperation(
519 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
520 operation) {
521 // Move operations don't require any data blob, so they can always
522 // be performed
523 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
524 return true;
525
526 // See if we have the entire data blob in the buffer
527 if (operation.data_offset() < buffer_offset_) {
528 LOG(ERROR) << "we threw away data it seems?";
529 return false;
530 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700531
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700532 return (operation.data_offset() + operation.data_length()) <=
533 (buffer_offset_ + buffer_.size());
534}
535
536bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700537 const DeltaArchiveManifest_InstallOperation& operation,
538 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700539 CHECK(operation.type() == \
540 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
541 operation.type() == \
542 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
543
544 // Since we delete data off the beginning of the buffer as we use it,
545 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700546 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
547 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700548
Darin Petkov437adc42010-10-07 13:12:24 -0700549 // Extract the signature message if it's in this operation.
550 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700551
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700552 DirectExtentWriter direct_writer;
553 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
554 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700555
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700556 // Since bzip decompression is optional, we have a variable writer that will
557 // point to one of the ExtentWriter objects above.
558 ExtentWriter* writer = NULL;
559 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
560 writer = &zero_pad_writer;
561 } else if (operation.type() ==
562 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
563 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
564 writer = bzip_writer.get();
565 } else {
566 NOTREACHED();
567 }
568
569 // Create a vector of extents to pass to the ExtentWriter.
570 vector<Extent> extents;
571 for (int i = 0; i < operation.dst_extents_size(); i++) {
572 extents.push_back(operation.dst_extents(i));
573 }
574
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700575 int fd = is_kernel_partition ? kernel_fd_ : fd_;
576
577 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700578 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
579 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700580
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700581 // Update buffer
582 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700583 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700584 return true;
585}
586
587bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700588 const DeltaArchiveManifest_InstallOperation& operation,
589 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700590 // Calculate buffer size. Note, this function doesn't do a sliding
591 // window to copy in case the source and destination blocks overlap.
592 // If we wanted to do a sliding window, we could program the server
593 // to generate deltas that effectively did a sliding window.
594
595 uint64_t blocks_to_read = 0;
596 for (int i = 0; i < operation.src_extents_size(); i++)
597 blocks_to_read += operation.src_extents(i).num_blocks();
598
599 uint64_t blocks_to_write = 0;
600 for (int i = 0; i < operation.dst_extents_size(); i++)
601 blocks_to_write += operation.dst_extents(i).num_blocks();
602
603 DCHECK_EQ(blocks_to_write, blocks_to_read);
604 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700605
606 int fd = is_kernel_partition ? kernel_fd_ : fd_;
607
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700608 // Read in bytes.
609 ssize_t bytes_read = 0;
610 for (int i = 0; i < operation.src_extents_size(); i++) {
611 ssize_t bytes_read_this_iteration = 0;
612 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200613 const size_t bytes = extent.num_blocks() * block_size_;
614 if (extent.start_block() == kSparseHole) {
615 bytes_read_this_iteration = bytes;
616 memset(&buf[bytes_read], 0, bytes);
617 } else {
618 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
619 &buf[bytes_read],
620 bytes,
621 extent.start_block() * block_size_,
622 &bytes_read_this_iteration));
623 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700624 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200625 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700626 bytes_read += bytes_read_this_iteration;
627 }
628
Darin Petkov45580e42010-10-08 14:02:40 -0700629 // If this is a non-idempotent operation, request a delayed exit and clear the
630 // update state in case the operation gets interrupted. Do this as late as
631 // possible.
632 if (!IsIdempotentOperation(operation)) {
633 Terminator::set_exit_blocked(true);
634 ResetUpdateProgress(prefs_, true);
635 }
636
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700637 // Write bytes out.
638 ssize_t bytes_written = 0;
639 for (int i = 0; i < operation.dst_extents_size(); i++) {
640 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200641 const size_t bytes = extent.num_blocks() * block_size_;
642 if (extent.start_block() == kSparseHole) {
Darin Petkov741a8222013-05-02 10:02:34 +0200643 DCHECK(buf.begin() + bytes_written ==
644 std::search_n(buf.begin() + bytes_written,
645 buf.begin() + bytes_written + bytes,
646 bytes, 0));
Darin Petkov8a075a72013-04-25 14:46:09 +0200647 } else {
648 TEST_AND_RETURN_FALSE(
649 utils::PWriteAll(fd,
650 &buf[bytes_written],
651 bytes,
652 extent.start_block() * block_size_));
653 }
654 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700655 }
656 DCHECK_EQ(bytes_written, bytes_read);
657 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
658 return true;
659}
660
661bool DeltaPerformer::ExtentsToBsdiffPositionsString(
662 const RepeatedPtrField<Extent>& extents,
663 uint64_t block_size,
664 uint64_t full_length,
665 string* positions_string) {
666 string ret;
667 uint64_t length = 0;
668 for (int i = 0; i < extents.size(); i++) {
669 Extent extent = extents.Get(i);
670 int64_t start = extent.start_block();
671 uint64_t this_length = min(full_length - length,
672 extent.num_blocks() * block_size);
673 if (start == static_cast<int64_t>(kSparseHole))
674 start = -1;
675 else
676 start *= block_size;
677 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
678 length += this_length;
679 }
680 TEST_AND_RETURN_FALSE(length == full_length);
681 if (!ret.empty())
682 ret.resize(ret.size() - 1); // Strip trailing comma off
683 *positions_string = ret;
684 return true;
685}
686
687bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700688 const DeltaArchiveManifest_InstallOperation& operation,
689 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700690 // Since we delete data off the beginning of the buffer as we use it,
691 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700692 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
693 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700694
695 string input_positions;
696 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
697 block_size_,
698 operation.src_length(),
699 &input_positions));
700 string output_positions;
701 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
702 block_size_,
703 operation.dst_length(),
704 &output_positions));
705
706 string temp_filename;
707 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
708 &temp_filename,
709 NULL));
710 ScopedPathUnlinker path_unlinker(temp_filename);
711 {
712 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
713 ScopedFdCloser fd_closer(&fd);
714 TEST_AND_RETURN_FALSE(
715 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
716 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700717
Darin Petkov7f2ec752013-04-03 14:45:19 +0200718 // Update the buffer to release the patch data memory as soon as the patch
719 // file is written out.
720 buffer_offset_ += operation.data_length();
721 DiscardBufferHeadBytes(operation.data_length());
722
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700723 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Darin Petkov3d1670d2013-07-12 14:37:06 +0200724 const string path = StringPrintf("/proc/self/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700725
Darin Petkov45580e42010-10-08 14:02:40 -0700726 // If this is a non-idempotent operation, request a delayed exit and clear the
727 // update state in case the operation gets interrupted. Do this as late as
728 // possible.
729 if (!IsIdempotentOperation(operation)) {
730 Terminator::set_exit_blocked(true);
731 ResetUpdateProgress(prefs_, true);
732 }
733
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700734 vector<string> cmd;
735 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700736 cmd.push_back(path);
737 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700738 cmd.push_back(temp_filename);
739 cmd.push_back(input_positions);
740 cmd.push_back(output_positions);
741 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700742 TEST_AND_RETURN_FALSE(
743 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700744 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700745 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700746 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700747 TEST_AND_RETURN_FALSE(return_code == 0);
748
749 if (operation.dst_length() % block_size_) {
750 // Zero out rest of final block.
751 // TODO(adlr): build this into bspatch; it's more efficient that way.
752 const Extent& last_extent =
753 operation.dst_extents(operation.dst_extents_size() - 1);
754 const uint64_t end_byte =
755 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
756 const uint64_t begin_byte =
757 end_byte - (block_size_ - operation.dst_length() % block_size_);
758 vector<char> zeros(end_byte - begin_byte);
759 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700760 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700761 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700762 return true;
763}
764
Darin Petkovd7061ab2010-10-06 14:37:09 -0700765bool DeltaPerformer::ExtractSignatureMessage(
766 const DeltaArchiveManifest_InstallOperation& operation) {
767 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
768 !manifest_.has_signatures_offset() ||
769 manifest_.signatures_offset() != operation.data_offset()) {
770 return false;
771 }
772 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
773 manifest_.signatures_size() == operation.data_length());
774 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
775 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
776 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700777 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700778 buffer_.begin(),
779 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700780
781 // Save the signature blob because if the update is interrupted after the
782 // download phase we don't go through this path anymore. Some alternatives to
783 // consider:
784 //
785 // 1. On resume, re-download the signature blob from the server and re-verify
786 // it.
787 //
788 // 2. Verify the signature as soon as it's received and don't checkpoint the
789 // blob and the signed sha-256 context.
790 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
791 string(&signatures_message_data_[0],
792 signatures_message_data_.size())))
793 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700794 // The hash of all data consumed so far should be verified against the signed
795 // hash.
796 signed_hash_context_ = hash_calculator_.GetContext();
797 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
798 signed_hash_context_))
799 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700800 LOG(INFO) << "Extracted signature data of size "
801 << manifest_.signatures_size() << " at "
802 << manifest_.signatures_offset();
803 return true;
804}
805
David Zeuthene7f89172013-10-31 10:21:04 -0700806bool DeltaPerformer::GetPublicKeyFromResponse(base::FilePath *out_tmp_key) {
807 if (system_state_->hardware()->IsOfficialBuild() ||
808 utils::FileExists(public_key_path_.c_str()) ||
809 install_plan_->public_key_rsa.empty())
810 return false;
811
812 if (!utils::DecodeAndStoreBase64String(install_plan_->public_key_rsa,
813 out_tmp_key))
814 return false;
815
816 return true;
817}
818
David Zeuthena99981f2013-04-29 13:42:47 -0700819ErrorCode DeltaPerformer::ValidateMetadataSignature(
Jay Srinivasanf4318702012-09-24 11:56:24 -0700820 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700821
Jay Srinivasanf4318702012-09-24 11:56:24 -0700822 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800823 if (install_plan_->hash_checks_mandatory) {
824 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700825 return kErrorCodeDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800826 }
827
828 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700829 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
David Zeuthena99981f2013-04-29 13:42:47 -0700830 SendUmaStat(kErrorCodeDownloadMetadataSignatureMissingError);
831 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700832 }
833
834 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700835 vector<char> metadata_signature;
836 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
837 &metadata_signature)) {
838 LOG(ERROR) << "Unable to decode base64 metadata signature: "
839 << install_plan_->metadata_signature;
David Zeuthena99981f2013-04-29 13:42:47 -0700840 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700841 }
842
David Zeuthene7f89172013-10-31 10:21:04 -0700843 // See if we should use the public RSA key in the Omaha response.
844 base::FilePath path_to_public_key(public_key_path_);
845 base::FilePath tmp_key;
846 if (GetPublicKeyFromResponse(&tmp_key))
847 path_to_public_key = tmp_key;
848 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
849 if (tmp_key.empty())
850 tmp_key_remover.set_should_remove(false);
851
852 LOG(INFO) << "Verifying metadata hash signature using public key: "
853 << path_to_public_key.value();
854
Jay Srinivasanf4318702012-09-24 11:56:24 -0700855 vector<char> expected_metadata_hash;
856 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
David Zeuthene7f89172013-10-31 10:21:04 -0700857 path_to_public_key.value(),
Jay Srinivasanf4318702012-09-24 11:56:24 -0700858 &expected_metadata_hash)) {
859 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
David Zeuthena99981f2013-04-29 13:42:47 -0700860 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700861 }
862
Jay Srinivasanf4318702012-09-24 11:56:24 -0700863 OmahaHashCalculator metadata_hasher;
864 metadata_hasher.Update(metadata, metadata_size);
865 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700866 LOG(ERROR) << "Unable to compute actual hash of manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700867 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700868 }
869
Jay Srinivasanf4318702012-09-24 11:56:24 -0700870 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
871 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
872 if (calculated_metadata_hash.empty()) {
873 LOG(ERROR) << "Computed actual hash of metadata is empty.";
David Zeuthena99981f2013-04-29 13:42:47 -0700874 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700875 }
876
Jay Srinivasanf4318702012-09-24 11:56:24 -0700877 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700878 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700879 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700880 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700881 utils::HexDumpVector(calculated_metadata_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700882 return kErrorCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700883 }
884
David Zeuthene7f89172013-10-31 10:21:04 -0700885 LOG(INFO) << "Metadata hash signature matches value in Omaha response.";
David Zeuthena99981f2013-04-29 13:42:47 -0700886 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700887}
888
Gilad Arnold21504f02013-05-24 08:51:22 -0700889ErrorCode DeltaPerformer::ValidateManifest() {
890 // Ensure that a full update does not contain old partition hashes, which is
891 // indicative of a delta.
892 //
893 // TODO(garnold) in general, the presence of an old partition hash should be
894 // the sole indicator for a delta update, as we would generally like update
895 // payloads to be self contained and not assume an Omaha response to tell us
896 // that. However, since this requires some massive reengineering of the update
897 // flow (making filesystem copying happen conditionally only *after*
898 // downloading and parsing of the update manifest) we'll put it off for now.
899 // See chromium-os:7597 for further discussion.
900 if (install_plan_->is_full_update &&
901 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info())) {
902 LOG(ERROR) << "Purported full payload contains old partition "
903 "hash(es), aborting update";
904 return kErrorCodePayloadMismatchedType;
905 }
906
907 // TODO(garnold) we should be adding more and more manifest checks, such as
908 // partition boundaries etc (see chromium-os:37661).
909
910 return kErrorCodeSuccess;
911}
912
David Zeuthena99981f2013-04-29 13:42:47 -0700913ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800914 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700915
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700916 if (!operation.data_sha256_hash().size()) {
917 if (!operation.data_length()) {
918 // Operations that do not have any data blob won't have any operation hash
919 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700920 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800921 // has already been validated. This is true for both HTTP and HTTPS cases.
David Zeuthena99981f2013-04-29 13:42:47 -0700922 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700923 }
924
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800925 // No hash is present for an operation that has data blobs. This shouldn't
926 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700927 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800928 // hashes. So if it happens it means either we've turned operation hash
929 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700930 // One caveat though: The last operation is a dummy signature operation
931 // that doesn't have a hash at the time the manifest is created. So we
932 // should not complaint about that operation. This operation can be
933 // recognized by the fact that it's offset is mentioned in the manifest.
934 if (manifest_.signatures_offset() &&
935 manifest_.signatures_offset() == operation.data_offset()) {
936 LOG(INFO) << "Skipping hash verification for signature operation "
937 << next_operation_num_ + 1;
938 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800939 if (install_plan_->hash_checks_mandatory) {
940 LOG(ERROR) << "Missing mandatory operation hash for operation "
941 << next_operation_num_ + 1;
David Zeuthena99981f2013-04-29 13:42:47 -0700942 return kErrorCodeDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800943 }
944
945 // For non-mandatory cases, just send a UMA stat.
946 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
947 << " as there's no operation hash in manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700948 SendUmaStat(kErrorCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700949 }
David Zeuthena99981f2013-04-29 13:42:47 -0700950 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700951 }
952
953 vector<char> expected_op_hash;
954 expected_op_hash.assign(operation.data_sha256_hash().data(),
955 (operation.data_sha256_hash().data() +
956 operation.data_sha256_hash().size()));
957
958 OmahaHashCalculator operation_hasher;
959 operation_hasher.Update(&buffer_[0], operation.data_length());
960 if (!operation_hasher.Finalize()) {
961 LOG(ERROR) << "Unable to compute actual hash of operation "
962 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700963 return kErrorCodeDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700964 }
965
966 vector<char> calculated_op_hash = operation_hasher.raw_hash();
967 if (calculated_op_hash != expected_op_hash) {
968 LOG(ERROR) << "Hash verification failed for operation "
969 << next_operation_num_ << ". Expected hash = ";
970 utils::HexDumpVector(expected_op_hash);
971 LOG(ERROR) << "Calculated hash over " << operation.data_length()
972 << " bytes at offset: " << operation.data_offset() << " = ";
973 utils::HexDumpVector(calculated_op_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700974 return kErrorCodeDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700975 }
976
David Zeuthena99981f2013-04-29 13:42:47 -0700977 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700978}
979
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700980#define TEST_AND_RETURN_VAL(_retval, _condition) \
981 do { \
982 if (!(_condition)) { \
983 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
984 return _retval; \
985 } \
986 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700987
David Zeuthena99981f2013-04-29 13:42:47 -0700988ErrorCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700989 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700990 const uint64_t update_check_response_size) {
David Zeuthene7f89172013-10-31 10:21:04 -0700991
992 // See if we should use the public RSA key in the Omaha response.
993 base::FilePath path_to_public_key(public_key_path_);
994 base::FilePath tmp_key;
995 if (GetPublicKeyFromResponse(&tmp_key))
996 path_to_public_key = tmp_key;
997 ScopedPathUnlinker tmp_key_remover(tmp_key.value());
998 if (tmp_key.empty())
999 tmp_key_remover.set_should_remove(false);
1000
1001 LOG(INFO) << "Verifying payload using public key: "
1002 << path_to_public_key.value();
Darin Petkov437adc42010-10-07 13:12:24 -07001003
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001004 // Verifies the download size.
David Zeuthena99981f2013-04-29 13:42:47 -07001005 TEST_AND_RETURN_VAL(kErrorCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -07001006 update_check_response_size ==
1007 manifest_metadata_size_ + buffer_offset_);
1008
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001009 // Verifies the payload hash.
1010 const string& payload_hash_data = hash_calculator_.hash();
David Zeuthena99981f2013-04-29 13:42:47 -07001011 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001012 !payload_hash_data.empty());
David Zeuthena99981f2013-04-29 13:42:47 -07001013 TEST_AND_RETURN_VAL(kErrorCodePayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001014 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -07001015
Darin Petkov437adc42010-10-07 13:12:24 -07001016 // Verifies the signed payload hash.
David Zeuthene7f89172013-10-31 10:21:04 -07001017 if (!utils::FileExists(path_to_public_key.value().c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -07001018 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
David Zeuthena99981f2013-04-29 13:42:47 -07001019 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001020 }
David Zeuthena99981f2013-04-29 13:42:47 -07001021 TEST_AND_RETURN_VAL(kErrorCodeSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001022 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -07001023 vector<char> signed_hash_data;
David Zeuthena99981f2013-04-29 13:42:47 -07001024 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001025 PayloadSigner::VerifySignature(
1026 signatures_message_data_,
David Zeuthene7f89172013-10-31 10:21:04 -07001027 path_to_public_key.value(),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001028 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -07001029 OmahaHashCalculator signed_hasher;
David Zeuthena99981f2013-04-29 13:42:47 -07001030 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001031 signed_hasher.SetContext(signed_hash_context_));
David Zeuthena99981f2013-04-29 13:42:47 -07001032 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001033 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -07001034 vector<char> hash_data = signed_hasher.raw_hash();
1035 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -07001036 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001037 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001038 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001039 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001040 "Attached Signature:";
1041 utils::HexDumpVector(signed_hash_data);
1042 LOG(ERROR) << "Computed Signature:";
1043 utils::HexDumpVector(hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -07001044 return kErrorCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -07001045 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001046
David Zeuthene7f89172013-10-31 10:21:04 -07001047 LOG(INFO) << "Payload hash matches value in payload.";
1048
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001049 // At this point, we are guaranteed to have downloaded a full payload, i.e
1050 // the one whose size matches the size mentioned in Omaha response. If any
1051 // errors happen after this, it's likely a problem with the payload itself or
1052 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -08001053 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001054 system_state_->payload_state()->DownloadComplete();
1055
David Zeuthena99981f2013-04-29 13:42:47 -07001056 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001057}
1058
Darin Petkov3aefa862010-12-07 14:45:00 -08001059bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
1060 vector<char>* kernel_hash,
1061 uint64_t* rootfs_size,
1062 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001063 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1064 manifest_.has_new_kernel_info() &&
1065 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001066 *kernel_size = manifest_.new_kernel_info().size();
1067 *rootfs_size = manifest_.new_rootfs_info().size();
1068 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1069 manifest_.new_kernel_info().hash().end());
1070 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1071 manifest_.new_rootfs_info().hash().end());
1072 kernel_hash->swap(new_kernel_hash);
1073 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001074 return true;
1075}
1076
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001077namespace {
1078void LogVerifyError(bool is_kern,
1079 const string& local_hash,
1080 const string& expected_hash) {
1081 const char* type = is_kern ? "kernel" : "rootfs";
1082 LOG(ERROR) << "This is a server-side error due to "
1083 << "mismatched delta update image!";
1084 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1085 << "update that must be applied over a " << type << " with "
1086 << "a specific checksum, but the " << type << " we're starting "
1087 << "with doesn't have that checksum! This means that "
1088 << "the delta I've been given doesn't match my existing "
1089 << "system. The " << type << " partition I have has hash: "
1090 << local_hash << " but the update expected me to have "
1091 << expected_hash << " .";
1092 if (is_kern) {
1093 LOG(INFO) << "To get the checksum of a kernel partition on a "
1094 << "booted machine, run this command (change /dev/sda2 "
1095 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1096 << "openssl dgst -sha256 -binary | openssl base64";
1097 } else {
1098 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1099 << "booted machine, run this command (change /dev/sda3 "
1100 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1101 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1102 << "| sed 's/[^0-9]*//') / 256 )) | "
1103 << "openssl dgst -sha256 -binary | openssl base64";
1104 }
1105 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1106 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1107}
1108
1109string StringForHashBytes(const void* bytes, size_t size) {
1110 string ret;
1111 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1112 ret = "<unknown>";
1113 }
1114 return ret;
1115}
1116} // namespace
1117
Darin Petkov698d0412010-10-13 10:59:44 -07001118bool DeltaPerformer::VerifySourcePartitions() {
1119 LOG(INFO) << "Verifying source partitions.";
1120 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001121 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001122 if (manifest_.has_old_kernel_info()) {
1123 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001124 bool valid =
1125 !install_plan_->kernel_hash.empty() &&
1126 install_plan_->kernel_hash.size() == info.hash().size() &&
1127 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001128 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001129 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001130 if (!valid) {
1131 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001132 StringForHashBytes(install_plan_->kernel_hash.data(),
1133 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001134 StringForHashBytes(info.hash().data(),
1135 info.hash().size()));
1136 }
1137 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001138 }
1139 if (manifest_.has_old_rootfs_info()) {
1140 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001141 bool valid =
1142 !install_plan_->rootfs_hash.empty() &&
1143 install_plan_->rootfs_hash.size() == info.hash().size() &&
1144 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001145 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001146 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001147 if (!valid) {
1148 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001149 StringForHashBytes(install_plan_->rootfs_hash.data(),
1150 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001151 StringForHashBytes(info.hash().data(),
1152 info.hash().size()));
1153 }
1154 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001155 }
1156 return true;
1157}
1158
Darin Petkov437adc42010-10-07 13:12:24 -07001159void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1160 hash_calculator_.Update(&buffer_[0], count);
Darin Petkov7f2ec752013-04-03 14:45:19 +02001161 // Copy the remainder data into a temporary vector first to ensure that any
1162 // unused memory in the updated |buffer_| will be released.
1163 vector<char> temp(buffer_.begin() + count, buffer_.end());
1164 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001165}
1166
Darin Petkov0406e402010-10-06 21:33:11 -07001167bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1168 string update_check_response_hash) {
1169 int64_t next_operation = kUpdateStateOperationInvalid;
1170 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1171 &next_operation) &&
1172 next_operation != kUpdateStateOperationInvalid &&
1173 next_operation > 0);
1174
1175 string interrupted_hash;
1176 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1177 &interrupted_hash) &&
David Zeuthenc41c2282013-06-17 16:33:06 -07001178 !interrupted_hash.empty() &&
1179 interrupted_hash == update_check_response_hash);
Darin Petkov0406e402010-10-06 21:33:11 -07001180
Darin Petkov61426142010-10-08 11:04:55 -07001181 int64_t resumed_update_failures;
1182 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1183 &resumed_update_failures) ||
1184 resumed_update_failures <= kMaxResumedUpdateFailures);
1185
Darin Petkov0406e402010-10-06 21:33:11 -07001186 // Sanity check the rest.
1187 int64_t next_data_offset = -1;
1188 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1189 &next_data_offset) &&
1190 next_data_offset >= 0);
1191
Darin Petkov437adc42010-10-07 13:12:24 -07001192 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001193 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001194 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1195 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001196
1197 int64_t manifest_metadata_size = 0;
1198 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1199 &manifest_metadata_size) &&
1200 manifest_metadata_size > 0);
1201
1202 return true;
1203}
1204
Darin Petkov9b230572010-10-08 10:20:09 -07001205bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001206 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1207 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001208 if (!quick) {
1209 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1210 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
David Zeuthen41996ad2013-09-24 15:43:24 -07001211 prefs->SetInt64(kPrefsUpdateStateNextDataLength, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001212 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1213 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001214 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001215 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001216 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001217 }
Darin Petkov73058b42010-10-06 16:32:19 -07001218 return true;
1219}
1220
1221bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001222 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001223 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001224 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001225 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001226 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001227 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001228 hash_calculator_.GetContext()));
1229 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1230 buffer_offset_));
1231 last_updated_buffer_offset_ = buffer_offset_;
David Zeuthen41996ad2013-09-24 15:43:24 -07001232
1233 if (next_operation_num_ < num_total_operations_) {
1234 const bool is_kernel_partition =
1235 next_operation_num_ >= num_rootfs_operations_;
1236 const DeltaArchiveManifest_InstallOperation &op =
1237 is_kernel_partition ?
1238 manifest_.kernel_install_operations(
1239 next_operation_num_ - num_rootfs_operations_) :
1240 manifest_.install_operations(next_operation_num_);
1241 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1242 op.data_length()));
1243 } else {
1244 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataLength,
1245 0));
1246 }
Darin Petkov0406e402010-10-06 21:33:11 -07001247 }
Darin Petkov73058b42010-10-06 16:32:19 -07001248 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1249 next_operation_num_));
1250 return true;
1251}
1252
Darin Petkov9b230572010-10-08 10:20:09 -07001253bool DeltaPerformer::PrimeUpdateState() {
1254 CHECK(manifest_valid_);
1255 block_size_ = manifest_.block_size();
1256
1257 int64_t next_operation = kUpdateStateOperationInvalid;
1258 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1259 next_operation == kUpdateStateOperationInvalid ||
1260 next_operation <= 0) {
1261 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001262 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001263 return true;
1264 }
1265 next_operation_num_ = next_operation;
1266
1267 // Resuming an update -- load the rest of the update state.
1268 int64_t next_data_offset = -1;
1269 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1270 &next_data_offset) &&
1271 next_data_offset >= 0);
1272 buffer_offset_ = next_data_offset;
1273
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001274 // The signed hash context and the signature blob may be empty if the
1275 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001276 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1277 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001278 string signature_blob;
1279 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1280 signatures_message_data_.assign(signature_blob.begin(),
1281 signature_blob.end());
1282 }
Darin Petkov9b230572010-10-08 10:20:09 -07001283
1284 string hash_context;
1285 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1286 &hash_context) &&
1287 hash_calculator_.SetContext(hash_context));
1288
1289 int64_t manifest_metadata_size = 0;
1290 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1291 &manifest_metadata_size) &&
1292 manifest_metadata_size > 0);
1293 manifest_metadata_size_ = manifest_metadata_size;
1294
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001295 // Advance the download progress to reflect what doesn't need to be
1296 // re-downloaded.
1297 total_bytes_received_ += buffer_offset_;
1298
Darin Petkov61426142010-10-08 11:04:55 -07001299 // Speculatively count the resume as a failure.
1300 int64_t resumed_update_failures;
1301 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1302 resumed_update_failures++;
1303 } else {
1304 resumed_update_failures = 1;
1305 }
1306 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001307 return true;
1308}
1309
David Zeuthena99981f2013-04-29 13:42:47 -07001310void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001311 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001312}
1313
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001314} // namespace chromeos_update_engine