blob: 46739b155a3f535bdac86e2f8e559cdd4c53c722 [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
Chris Masoned903c3b2011-05-12 15:35:46 -070015#include <base/memory/scoped_ptr.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070016#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040017#include <base/stringprintf.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070018#include <google/protobuf/repeated_field.h>
19
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070020#include "update_engine/bzip_extent_writer.h"
21#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070022#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/extent_writer.h"
24#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070025#include "update_engine/payload_signer.h"
Darin Petkov73058b42010-10-06 16:32:19 -070026#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070027#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070028#include "update_engine/terminator.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070029
30using std::min;
31using std::string;
32using std::vector;
33using google::protobuf::RepeatedPtrField;
34
35namespace chromeos_update_engine {
36
Darin Petkovabc7bc02011-02-23 14:39:43 -080037const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
38 "/usr/share/update_engine/update-payload-key.pub.pem";
39
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040namespace {
41
42const int kDeltaVersionLength = 8;
43const int kDeltaProtobufLengthLength = 8;
Darin Petkov73058b42010-10-06 16:32:19 -070044const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070045const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070046
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070047// Converts extents to a human-readable string, for use by DumpUpdateProto().
48string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
49 string ret;
50 for (int i = 0; i < extents.size(); i++) {
51 const Extent& extent = extents.Get(i);
52 if (extent.start_block() == kSparseHole) {
53 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
54 } else {
55 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
56 extent.start_block(), extent.num_blocks());
57 }
58 }
59 if (!ret.empty()) {
60 DCHECK_GT(ret.size(), static_cast<size_t>(1));
61 ret.resize(ret.size() - 2);
62 }
63 return ret;
64}
65
66// LOGs a DeltaArchiveManifest object. Useful for debugging.
67void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
68 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070069 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070070 for (int i = 0; i < (manifest.install_operations_size() +
71 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070072 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070073 i < manifest.install_operations_size() ?
74 manifest.install_operations(i) :
75 manifest.kernel_install_operations(
76 i - manifest.install_operations_size());
77 if (i == 0)
78 LOG(INFO) << " Rootfs ops:";
79 else if (i == manifest.install_operations_size())
80 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070081 LOG(INFO) << " operation(" << i << ")";
82 LOG(INFO) << " type: "
83 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
84 if (op.has_data_offset())
85 LOG(INFO) << " data_offset: " << op.data_offset();
86 if (op.has_data_length())
87 LOG(INFO) << " data_length: " << op.data_length();
88 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
89 if (op.has_src_length())
90 LOG(INFO) << " src_length: " << op.src_length();
91 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
92 if (op.has_dst_length())
93 LOG(INFO) << " dst_length: " << op.dst_length();
94 }
95}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070096
97// Opens path for read/write, put the fd into *fd. On success returns true
98// and sets *err to 0. On failure, returns false and sets *err to errno.
99bool OpenFile(const char* path, int* fd, int* err) {
100 if (*fd != -1) {
101 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
102 *err = EINVAL;
103 return false;
104 }
105 *fd = open(path, O_RDWR, 000);
106 if (*fd < 0) {
107 *err = errno;
108 PLOG(ERROR) << "Unable to open file " << path;
109 return false;
110 }
111 *err = 0;
112 return true;
113}
114
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700115} // namespace {}
116
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700117// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
118// it safely. Returns false otherwise.
119bool DeltaPerformer::IsIdempotentOperation(
120 const DeltaArchiveManifest_InstallOperation& op) {
121 if (op.src_extents_size() == 0) {
122 return true;
123 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700124 // When in doubt, it's safe to declare an op non-idempotent. Note that we
125 // could detect other types of idempotent operations here such as a MOVE that
126 // moves blocks onto themselves. However, we rely on the server to not send
127 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700128 ExtentRanges src_ranges;
129 src_ranges.AddRepeatedExtents(op.src_extents());
130 const uint64_t block_count = src_ranges.blocks();
131 src_ranges.SubtractRepeatedExtents(op.dst_extents());
132 return block_count == src_ranges.blocks();
133}
134
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700135int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700136 int err;
137 if (OpenFile(path, &fd_, &err))
138 path_ = path;
139 return -err;
140}
141
142bool DeltaPerformer::OpenKernel(const char* kernel_path) {
143 int err;
144 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
145 if (success)
146 kernel_path_ = kernel_path;
147 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700148}
149
150int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700151 int err = 0;
152 if (close(kernel_fd_) == -1) {
153 err = errno;
154 PLOG(ERROR) << "Unable to close kernel fd:";
155 }
156 if (close(fd_) == -1) {
157 err = errno;
158 PLOG(ERROR) << "Unable to close rootfs fd:";
159 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700160 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800161 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800163 if (!buffer_.empty()) {
164 LOG(ERROR) << "Called Close() while buffer not empty!";
165 if (err >= 0) {
166 err = 1;
167 }
168 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700169 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700170}
171
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700172namespace {
173
174void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
175 string sha256;
176 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
177 info.hash().size(),
178 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800179 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
180 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700181 } else {
182 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
183 }
184}
185
186void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
187 if (manifest.has_old_kernel_info())
188 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
189 if (manifest.has_old_rootfs_info())
190 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
191 if (manifest.has_new_kernel_info())
192 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
193 if (manifest.has_new_rootfs_info())
194 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
195}
196
197} // namespace {}
198
Darin Petkov9574f7e2011-01-13 10:48:12 -0800199DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
200 const std::vector<char>& payload,
201 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700202 uint64_t* metadata_size,
203 ActionExitCode* error) {
204 *error = kActionCodeSuccess;
205
206 const uint64_t protobuf_offset = strlen(kDeltaMagic) + kDeltaVersionLength +
207 kDeltaProtobufLengthLength;
208 if (payload.size() < protobuf_offset) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800209 // Don't have enough bytes to know the protobuf length.
210 return kMetadataParseInsufficientData;
211 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700212
213 // Validate the magic number.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800214 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
215 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700216 *error = kActionCodeDownloadInvalidManifest;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800217 return kMetadataParseError;
218 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700219
220 // TODO(jaysri): Compare the version number and skip unknown manifest
221 // versions. We don't check the version at all today.
222
223 // Next, parse the proto buf length.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800224 uint64_t protobuf_length;
225 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
226 protobuf_length_size_mismatch);
227 memcpy(&protobuf_length,
228 &payload[strlen(kDeltaMagic) + kDeltaVersionLength],
229 kDeltaProtobufLengthLength);
230 protobuf_length = be64toh(protobuf_length); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700231
232 // Now, check if the metasize we computed matches what was passed in
233 // through Omaha Response.
234 *metadata_size = protobuf_offset + protobuf_length;
235
236 // If the manifest size is present in install plan, check for it immediately
237 // even before waiting for that many number of bytes to be downloaded
238 // in the payload. This will prevent any attack which relies on us downloading
239 // data beyond the expected manifest size.
240 if (install_plan_->manifest_size > 0 &&
241 install_plan_->manifest_size != *metadata_size) {
242 LOG(ERROR) << "Invalid manifest size. Expected = "
243 << install_plan_->manifest_size
244 << "Actual = " << *metadata_size;
245 // TODO(jaysri): Add a UMA Stat here to help with the decision to enforce
246 // this check in a future release, as mentioned below.
247
248 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
249 // error. But in the next release, we should uncomment the lines below.
250 // *error = kActionCodeDownloadInvalidManifest;
251 // return kMetadataParseError;
252 }
253
254 // Now that we have validated the metadata size, we should wait for the full
255 // metadata to be read in before we can parse it.
256 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800257 return kMetadataParseInsufficientData;
258 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700259
260 // Log whether we validated the size or simply trusting what's in the payload
261 // here. This is logged here (after we received the full manifest data) so
262 // that we just log once (instead of logging n times) if it takes n
263 // DeltaPerformer::Write calls to download the full manifest.
264 if (install_plan_->manifest_size == 0)
265 LOG(WARNING) << "No manifest size specified in Omaha. "
266 << "Trusting manifest size in payload = " << *metadata_size;
267 else
268 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
269
270 // We have the full proto buffer in |payload|. Verify its integrity
271 // and authenticity based on what Omaha says.
272 *error = ValidateManifestSignature(&payload[protobuf_offset],
273 protobuf_length);
274 if (*error != kActionCodeSuccess) {
275 // TODO(jaysri): Add a UMA Stat here to help with the decision to enforce
276 // this check in a future release, as mentioned below.
277
278 // TODO(jaysri): VALIDATION: Initially we don't want to make this a fatal
279 // error. But in the next release, we should remove the line below and
280 // return an error.
281 *error = kActionCodeSuccess;
282 }
283
284 // The proto buffer in |payload| is deemed valid. Parse it.
285 if (!manifest->ParseFromArray(&payload[protobuf_offset], protobuf_length)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800286 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700287 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800288 return kMetadataParseError;
289 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800290 return kMetadataParseSuccess;
291}
292
293
Don Garrette410e0f2011-11-10 15:39:01 -0800294// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700295// were written, or false on any error, reguardless of progress
296// and stores an action exit code in |error|.
297bool DeltaPerformer::Write(const void* bytes, size_t count,
298 ActionExitCode *error) {
299 *error = kActionCodeSuccess;
300
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700301 const char* c_bytes = reinterpret_cast<const char*>(bytes);
302 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700303 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800304 MetadataParseResult result = ParsePayloadMetadata(buffer_,
305 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700306 &manifest_metadata_size_,
307 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800308 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800309 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800310 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800311 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800312 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700313 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700314 // Remove protobuf and header info from buffer_, so buffer_ contains
315 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700316 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700317 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700318 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700319 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700320 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700321
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700322 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700323 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700324 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700325 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800326 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700327 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700328 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700329 ssize_t total_operations = manifest_.install_operations_size() +
330 manifest_.kernel_install_operations_size();
331 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700332 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700333 next_operation_num_ < manifest_.install_operations_size() ?
334 manifest_.install_operations(next_operation_num_) :
335 manifest_.kernel_install_operations(
336 next_operation_num_ - manifest_.install_operations_size());
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700337 if (!CanPerformInstallOperation(op)) {
338 // This means we don't have enough bytes received yet to carry out the
339 // next operation.
340 return true;
341 }
342
343 *error = ValidateOperationHash(op);
344 if (*error != kActionCodeSuccess) {
345 // Cannot proceed further as operation hash is invalid.
346 // Higher level code will take care of retrying appropriately.
347 return false;
348 }
349
Darin Petkov45580e42010-10-08 14:02:40 -0700350 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700351 ScopedTerminatorExitUnblocker exit_unblocker =
352 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700353 // Log every thousandth operation, and also the first and last ones
354 if ((next_operation_num_ % 1000 == 0) ||
355 (next_operation_num_ + 1 == total_operations)) {
356 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
357 << total_operations;
358 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700359 bool is_kernel_partition =
360 (next_operation_num_ >= manifest_.install_operations_size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700361 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
362 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700363 if (!PerformReplaceOperation(op, is_kernel_partition)) {
364 LOG(ERROR) << "Failed to perform replace operation "
365 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700366 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800367 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700368 }
369 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700370 if (!PerformMoveOperation(op, is_kernel_partition)) {
371 LOG(ERROR) << "Failed to perform move operation "
372 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700373 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800374 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700375 }
376 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700377 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
378 LOG(ERROR) << "Failed to perform bsdiff operation "
379 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700380 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800381 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700382 }
383 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700384 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700385 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700386 }
Don Garrette410e0f2011-11-10 15:39:01 -0800387 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700388}
389
390bool DeltaPerformer::CanPerformInstallOperation(
391 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
392 operation) {
393 // Move operations don't require any data blob, so they can always
394 // be performed
395 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
396 return true;
397
398 // See if we have the entire data blob in the buffer
399 if (operation.data_offset() < buffer_offset_) {
400 LOG(ERROR) << "we threw away data it seems?";
401 return false;
402 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700403
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700404 return (operation.data_offset() + operation.data_length()) <=
405 (buffer_offset_ + buffer_.size());
406}
407
408bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700409 const DeltaArchiveManifest_InstallOperation& operation,
410 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700411 CHECK(operation.type() == \
412 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
413 operation.type() == \
414 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
415
416 // Since we delete data off the beginning of the buffer as we use it,
417 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700418 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
419 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700420
Darin Petkov437adc42010-10-07 13:12:24 -0700421 // Extract the signature message if it's in this operation.
422 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700423
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700424 DirectExtentWriter direct_writer;
425 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
426 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700427
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700428 // Since bzip decompression is optional, we have a variable writer that will
429 // point to one of the ExtentWriter objects above.
430 ExtentWriter* writer = NULL;
431 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
432 writer = &zero_pad_writer;
433 } else if (operation.type() ==
434 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
435 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
436 writer = bzip_writer.get();
437 } else {
438 NOTREACHED();
439 }
440
441 // Create a vector of extents to pass to the ExtentWriter.
442 vector<Extent> extents;
443 for (int i = 0; i < operation.dst_extents_size(); i++) {
444 extents.push_back(operation.dst_extents(i));
445 }
446
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700447 int fd = is_kernel_partition ? kernel_fd_ : fd_;
448
449 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700450 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
451 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700452
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700453 // Update buffer
454 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700455 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700456 return true;
457}
458
459bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700460 const DeltaArchiveManifest_InstallOperation& operation,
461 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700462 // Calculate buffer size. Note, this function doesn't do a sliding
463 // window to copy in case the source and destination blocks overlap.
464 // If we wanted to do a sliding window, we could program the server
465 // to generate deltas that effectively did a sliding window.
466
467 uint64_t blocks_to_read = 0;
468 for (int i = 0; i < operation.src_extents_size(); i++)
469 blocks_to_read += operation.src_extents(i).num_blocks();
470
471 uint64_t blocks_to_write = 0;
472 for (int i = 0; i < operation.dst_extents_size(); i++)
473 blocks_to_write += operation.dst_extents(i).num_blocks();
474
475 DCHECK_EQ(blocks_to_write, blocks_to_read);
476 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700477
478 int fd = is_kernel_partition ? kernel_fd_ : fd_;
479
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700480 // Read in bytes.
481 ssize_t bytes_read = 0;
482 for (int i = 0; i < operation.src_extents_size(); i++) {
483 ssize_t bytes_read_this_iteration = 0;
484 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700485 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700486 &buf[bytes_read],
487 extent.num_blocks() * block_size_,
488 extent.start_block() * block_size_,
489 &bytes_read_this_iteration));
490 TEST_AND_RETURN_FALSE(
491 bytes_read_this_iteration ==
492 static_cast<ssize_t>(extent.num_blocks() * block_size_));
493 bytes_read += bytes_read_this_iteration;
494 }
495
Darin Petkov45580e42010-10-08 14:02:40 -0700496 // If this is a non-idempotent operation, request a delayed exit and clear the
497 // update state in case the operation gets interrupted. Do this as late as
498 // possible.
499 if (!IsIdempotentOperation(operation)) {
500 Terminator::set_exit_blocked(true);
501 ResetUpdateProgress(prefs_, true);
502 }
503
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700504 // Write bytes out.
505 ssize_t bytes_written = 0;
506 for (int i = 0; i < operation.dst_extents_size(); i++) {
507 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700508 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700509 &buf[bytes_written],
510 extent.num_blocks() * block_size_,
511 extent.start_block() * block_size_));
512 bytes_written += extent.num_blocks() * block_size_;
513 }
514 DCHECK_EQ(bytes_written, bytes_read);
515 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
516 return true;
517}
518
519bool DeltaPerformer::ExtentsToBsdiffPositionsString(
520 const RepeatedPtrField<Extent>& extents,
521 uint64_t block_size,
522 uint64_t full_length,
523 string* positions_string) {
524 string ret;
525 uint64_t length = 0;
526 for (int i = 0; i < extents.size(); i++) {
527 Extent extent = extents.Get(i);
528 int64_t start = extent.start_block();
529 uint64_t this_length = min(full_length - length,
530 extent.num_blocks() * block_size);
531 if (start == static_cast<int64_t>(kSparseHole))
532 start = -1;
533 else
534 start *= block_size;
535 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
536 length += this_length;
537 }
538 TEST_AND_RETURN_FALSE(length == full_length);
539 if (!ret.empty())
540 ret.resize(ret.size() - 1); // Strip trailing comma off
541 *positions_string = ret;
542 return true;
543}
544
545bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700546 const DeltaArchiveManifest_InstallOperation& operation,
547 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700548 // Since we delete data off the beginning of the buffer as we use it,
549 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700550 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
551 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700552
553 string input_positions;
554 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
555 block_size_,
556 operation.src_length(),
557 &input_positions));
558 string output_positions;
559 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
560 block_size_,
561 operation.dst_length(),
562 &output_positions));
563
564 string temp_filename;
565 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
566 &temp_filename,
567 NULL));
568 ScopedPathUnlinker path_unlinker(temp_filename);
569 {
570 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
571 ScopedFdCloser fd_closer(&fd);
572 TEST_AND_RETURN_FALSE(
573 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
574 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700575
576 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700577 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700578
Darin Petkov45580e42010-10-08 14:02:40 -0700579 // If this is a non-idempotent operation, request a delayed exit and clear the
580 // update state in case the operation gets interrupted. Do this as late as
581 // possible.
582 if (!IsIdempotentOperation(operation)) {
583 Terminator::set_exit_blocked(true);
584 ResetUpdateProgress(prefs_, true);
585 }
586
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700587 vector<string> cmd;
588 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700589 cmd.push_back(path);
590 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700591 cmd.push_back(temp_filename);
592 cmd.push_back(input_positions);
593 cmd.push_back(output_positions);
594 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700595 TEST_AND_RETURN_FALSE(
596 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700597 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700598 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700599 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700600 TEST_AND_RETURN_FALSE(return_code == 0);
601
602 if (operation.dst_length() % block_size_) {
603 // Zero out rest of final block.
604 // TODO(adlr): build this into bspatch; it's more efficient that way.
605 const Extent& last_extent =
606 operation.dst_extents(operation.dst_extents_size() - 1);
607 const uint64_t end_byte =
608 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
609 const uint64_t begin_byte =
610 end_byte - (block_size_ - operation.dst_length() % block_size_);
611 vector<char> zeros(end_byte - begin_byte);
612 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700613 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700614 }
615
616 // Update buffer.
617 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700618 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700619 return true;
620}
621
Darin Petkovd7061ab2010-10-06 14:37:09 -0700622bool DeltaPerformer::ExtractSignatureMessage(
623 const DeltaArchiveManifest_InstallOperation& operation) {
624 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
625 !manifest_.has_signatures_offset() ||
626 manifest_.signatures_offset() != operation.data_offset()) {
627 return false;
628 }
629 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
630 manifest_.signatures_size() == operation.data_length());
631 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
632 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
633 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700634 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700635 buffer_.begin(),
636 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700637
638 // Save the signature blob because if the update is interrupted after the
639 // download phase we don't go through this path anymore. Some alternatives to
640 // consider:
641 //
642 // 1. On resume, re-download the signature blob from the server and re-verify
643 // it.
644 //
645 // 2. Verify the signature as soon as it's received and don't checkpoint the
646 // blob and the signed sha-256 context.
647 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
648 string(&signatures_message_data_[0],
649 signatures_message_data_.size())))
650 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700651 // The hash of all data consumed so far should be verified against the signed
652 // hash.
653 signed_hash_context_ = hash_calculator_.GetContext();
654 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
655 signed_hash_context_))
656 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700657 LOG(INFO) << "Extracted signature data of size "
658 << manifest_.signatures_size() << " at "
659 << manifest_.signatures_offset();
660 return true;
661}
662
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700663ActionExitCode DeltaPerformer::ValidateManifestSignature(
664 const char* protobuf, uint64_t protobuf_length) {
665
666 if (install_plan_->manifest_signature.empty()) {
667 // If this is not present, we cannot validate the manifest. This should
668 // never happen in normal circumstances, but this can be used as a
669 // release-knob to turn off the new code path that verify per-operation
670 // hashes. So, for now, we should not treat this as a failure. Once we are
671 // confident this path is bug-free, we should treat this as a failure so
672 // that we remain robust even if the connection to Omaha is subjected to
673 // any SSL attack.
674 LOG(WARNING) << "Cannot validate manifest as the signature is empty";
675 return kActionCodeSuccess;
676 }
677
678 // Convert base64-encoded signature to raw bytes.
679 vector<char> manifest_signature;
680 if (!OmahaHashCalculator::Base64Decode(install_plan_->manifest_signature,
681 &manifest_signature)) {
682 LOG(ERROR) << "Unable to decode base64 manifest signature: "
683 << install_plan_->manifest_signature;
684 return kActionCodeDownloadManifestSignatureError;
685 }
686
687 vector<char> expected_manifest_hash;
688 if (!PayloadSigner::GetRawHashFromSignature(manifest_signature,
689 public_key_path_,
690 &expected_manifest_hash)) {
691 LOG(ERROR) << "Unable to compute expected hash from manifest signature";
692 return kActionCodeDownloadManifestSignatureError;
693 }
694
695 OmahaHashCalculator manifest_hasher;
696 manifest_hasher.Update(protobuf, protobuf_length);
697 if (!manifest_hasher.Finalize()) {
698 LOG(ERROR) << "Unable to compute actual hash of manifest";
699 return kActionCodeDownloadManifestSignatureVerificationError;
700 }
701
702 vector<char> calculated_manifest_hash = manifest_hasher.raw_hash();
703 PayloadSigner::PadRSA2048SHA256Hash(&calculated_manifest_hash);
704 if (calculated_manifest_hash.empty()) {
705 LOG(ERROR) << "Computed actual hash of manifest is empty.";
706 return kActionCodeDownloadManifestSignatureVerificationError;
707 }
708
709 if (calculated_manifest_hash != expected_manifest_hash) {
710 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
711 utils::HexDumpVector(expected_manifest_hash);
712 LOG(ERROR) << "Calculated hash = ";
713 utils::HexDumpVector(calculated_manifest_hash);
714 return kActionCodeDownloadManifestSignatureMismatch;
715 }
716
717 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
718 return kActionCodeSuccess;
719}
720
721ActionExitCode DeltaPerformer::ValidateOperationHash(
722 const DeltaArchiveManifest_InstallOperation&
723 operation) {
724
725 // TODO(jaysri): To be implemented.
726 return kActionCodeSuccess;
727}
728
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700729#define TEST_AND_RETURN_VAL(_retval, _condition) \
730 do { \
731 if (!(_condition)) { \
732 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
733 return _retval; \
734 } \
735 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700736
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700737ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700738 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700739 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700740 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700741
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700742 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700743 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700744 update_check_response_size ==
745 manifest_metadata_size_ + buffer_offset_);
746
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700747 // Verifies the payload hash.
748 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700749 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700750 !payload_hash_data.empty());
751 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
752 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700753
Darin Petkov437adc42010-10-07 13:12:24 -0700754 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700755 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700756 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700757 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700758 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700759 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
760 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700761 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700762 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
763 PayloadSigner::VerifySignature(
764 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700765 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700766 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700767 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700768 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
769 signed_hasher.SetContext(signed_hash_context_));
770 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
771 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700772 vector<char> hash_data = signed_hasher.raw_hash();
773 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700774 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
775 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700776 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700777 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700778 "Attached Signature:";
779 utils::HexDumpVector(signed_hash_data);
780 LOG(ERROR) << "Computed Signature:";
781 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700782 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700783 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700784 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700785}
786
Darin Petkov3aefa862010-12-07 14:45:00 -0800787bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
788 vector<char>* kernel_hash,
789 uint64_t* rootfs_size,
790 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700791 TEST_AND_RETURN_FALSE(manifest_valid_ &&
792 manifest_.has_new_kernel_info() &&
793 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800794 *kernel_size = manifest_.new_kernel_info().size();
795 *rootfs_size = manifest_.new_rootfs_info().size();
796 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
797 manifest_.new_kernel_info().hash().end());
798 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
799 manifest_.new_rootfs_info().hash().end());
800 kernel_hash->swap(new_kernel_hash);
801 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700802 return true;
803}
804
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700805namespace {
806void LogVerifyError(bool is_kern,
807 const string& local_hash,
808 const string& expected_hash) {
809 const char* type = is_kern ? "kernel" : "rootfs";
810 LOG(ERROR) << "This is a server-side error due to "
811 << "mismatched delta update image!";
812 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
813 << "update that must be applied over a " << type << " with "
814 << "a specific checksum, but the " << type << " we're starting "
815 << "with doesn't have that checksum! This means that "
816 << "the delta I've been given doesn't match my existing "
817 << "system. The " << type << " partition I have has hash: "
818 << local_hash << " but the update expected me to have "
819 << expected_hash << " .";
820 if (is_kern) {
821 LOG(INFO) << "To get the checksum of a kernel partition on a "
822 << "booted machine, run this command (change /dev/sda2 "
823 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
824 << "openssl dgst -sha256 -binary | openssl base64";
825 } else {
826 LOG(INFO) << "To get the checksum of a rootfs partition on a "
827 << "booted machine, run this command (change /dev/sda3 "
828 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
829 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
830 << "| sed 's/[^0-9]*//') / 256 )) | "
831 << "openssl dgst -sha256 -binary | openssl base64";
832 }
833 LOG(INFO) << "To get the checksum of partitions in a bin file, "
834 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
835}
836
837string StringForHashBytes(const void* bytes, size_t size) {
838 string ret;
839 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
840 ret = "<unknown>";
841 }
842 return ret;
843}
844} // namespace
845
Darin Petkov698d0412010-10-13 10:59:44 -0700846bool DeltaPerformer::VerifySourcePartitions() {
847 LOG(INFO) << "Verifying source partitions.";
848 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700849 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -0700850 if (manifest_.has_old_kernel_info()) {
851 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700852 bool valid =
853 !install_plan_->kernel_hash.empty() &&
854 install_plan_->kernel_hash.size() == info.hash().size() &&
855 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700856 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700857 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700858 if (!valid) {
859 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700860 StringForHashBytes(install_plan_->kernel_hash.data(),
861 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700862 StringForHashBytes(info.hash().data(),
863 info.hash().size()));
864 }
865 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700866 }
867 if (manifest_.has_old_rootfs_info()) {
868 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700869 bool valid =
870 !install_plan_->rootfs_hash.empty() &&
871 install_plan_->rootfs_hash.size() == info.hash().size() &&
872 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700873 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700874 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700875 if (!valid) {
876 LogVerifyError(false,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700877 StringForHashBytes(install_plan_->kernel_hash.data(),
878 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700879 StringForHashBytes(info.hash().data(),
880 info.hash().size()));
881 }
882 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700883 }
884 return true;
885}
886
Darin Petkov437adc42010-10-07 13:12:24 -0700887void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
888 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700889 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
890}
891
Darin Petkov0406e402010-10-06 21:33:11 -0700892bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
893 string update_check_response_hash) {
894 int64_t next_operation = kUpdateStateOperationInvalid;
895 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
896 &next_operation) &&
897 next_operation != kUpdateStateOperationInvalid &&
898 next_operation > 0);
899
900 string interrupted_hash;
901 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
902 &interrupted_hash) &&
903 !interrupted_hash.empty() &&
904 interrupted_hash == update_check_response_hash);
905
Darin Petkov61426142010-10-08 11:04:55 -0700906 int64_t resumed_update_failures;
907 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
908 &resumed_update_failures) ||
909 resumed_update_failures <= kMaxResumedUpdateFailures);
910
Darin Petkov0406e402010-10-06 21:33:11 -0700911 // Sanity check the rest.
912 int64_t next_data_offset = -1;
913 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
914 &next_data_offset) &&
915 next_data_offset >= 0);
916
Darin Petkov437adc42010-10-07 13:12:24 -0700917 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700918 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700919 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
920 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700921
922 int64_t manifest_metadata_size = 0;
923 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
924 &manifest_metadata_size) &&
925 manifest_metadata_size > 0);
926
927 return true;
928}
929
Darin Petkov9b230572010-10-08 10:20:09 -0700930bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -0700931 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
932 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -0700933 if (!quick) {
934 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
935 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
936 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
937 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700938 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -0700939 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -0700940 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -0700941 }
Darin Petkov73058b42010-10-06 16:32:19 -0700942 return true;
943}
944
945bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700946 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -0700947 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700948 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -0700949 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -0700950 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700951 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -0700952 hash_calculator_.GetContext()));
953 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
954 buffer_offset_));
955 last_updated_buffer_offset_ = buffer_offset_;
956 }
Darin Petkov73058b42010-10-06 16:32:19 -0700957 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
958 next_operation_num_));
959 return true;
960}
961
Darin Petkov9b230572010-10-08 10:20:09 -0700962bool DeltaPerformer::PrimeUpdateState() {
963 CHECK(manifest_valid_);
964 block_size_ = manifest_.block_size();
965
966 int64_t next_operation = kUpdateStateOperationInvalid;
967 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
968 next_operation == kUpdateStateOperationInvalid ||
969 next_operation <= 0) {
970 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -0700971 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -0700972 return true;
973 }
974 next_operation_num_ = next_operation;
975
976 // Resuming an update -- load the rest of the update state.
977 int64_t next_data_offset = -1;
978 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
979 &next_data_offset) &&
980 next_data_offset >= 0);
981 buffer_offset_ = next_data_offset;
982
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700983 // The signed hash context and the signature blob may be empty if the
984 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -0700985 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
986 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700987 string signature_blob;
988 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
989 signatures_message_data_.assign(signature_blob.begin(),
990 signature_blob.end());
991 }
Darin Petkov9b230572010-10-08 10:20:09 -0700992
993 string hash_context;
994 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
995 &hash_context) &&
996 hash_calculator_.SetContext(hash_context));
997
998 int64_t manifest_metadata_size = 0;
999 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1000 &manifest_metadata_size) &&
1001 manifest_metadata_size > 0);
1002 manifest_metadata_size_ = manifest_metadata_size;
1003
Darin Petkov61426142010-10-08 11:04:55 -07001004 // Speculatively count the resume as a failure.
1005 int64_t resumed_update_failures;
1006 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1007 resumed_update_failures++;
1008 } else {
1009 resumed_update_failures = 1;
1010 }
1011 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001012 return true;
1013}
1014
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001015} // namespace chromeos_update_engine