blob: 4d6df80b6411dcb03e30e37cdd9c5dd296fc1444 [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,
202 uint64_t* metadata_size) {
203 if (payload.size() < strlen(kDeltaMagic) +
204 kDeltaVersionLength + kDeltaProtobufLengthLength) {
205 // Don't have enough bytes to know the protobuf length.
206 return kMetadataParseInsufficientData;
207 }
208 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
209 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
210 return kMetadataParseError;
211 }
212 uint64_t protobuf_length;
213 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
214 protobuf_length_size_mismatch);
215 memcpy(&protobuf_length,
216 &payload[strlen(kDeltaMagic) + kDeltaVersionLength],
217 kDeltaProtobufLengthLength);
218 protobuf_length = be64toh(protobuf_length); // switch big endian to host
219 if (payload.size() < strlen(kDeltaMagic) + kDeltaVersionLength +
220 kDeltaProtobufLengthLength + protobuf_length) {
221 return kMetadataParseInsufficientData;
222 }
223 // We have the full proto buffer in |payload|. Parse it.
224 const int offset = strlen(kDeltaMagic) + kDeltaVersionLength +
225 kDeltaProtobufLengthLength;
226 if (!manifest->ParseFromArray(&payload[offset], protobuf_length)) {
227 LOG(ERROR) << "Unable to parse manifest in update file.";
228 return kMetadataParseError;
229 }
230 *metadata_size = strlen(kDeltaMagic) + kDeltaVersionLength +
231 kDeltaProtobufLengthLength + protobuf_length;
232 return kMetadataParseSuccess;
233}
234
235
Don Garrette410e0f2011-11-10 15:39:01 -0800236// Wrapper around write. Returns true if all requested bytes
237// were written, or false on any error, reguardless of progress.
238bool DeltaPerformer::Write(const void* bytes, size_t count) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700239 const char* c_bytes = reinterpret_cast<const char*>(bytes);
240 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
241
242 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800243 MetadataParseResult result = ParsePayloadMetadata(buffer_,
244 &manifest_,
245 &manifest_metadata_size_);
246 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800247 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800248 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800249 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800250 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700251 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700252 // Remove protobuf and header info from buffer_, so buffer_ contains
253 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700254 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700255 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700256 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700257 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700258 manifest_valid_ = true;
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700259 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700260 if (!PrimeUpdateState()) {
261 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800262 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700263 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700264 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700265 ssize_t total_operations = manifest_.install_operations_size() +
266 manifest_.kernel_install_operations_size();
267 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700268 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700269 next_operation_num_ < manifest_.install_operations_size() ?
270 manifest_.install_operations(next_operation_num_) :
271 manifest_.kernel_install_operations(
272 next_operation_num_ - manifest_.install_operations_size());
273 if (!CanPerformInstallOperation(op))
274 break;
Darin Petkov45580e42010-10-08 14:02:40 -0700275 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700276 ScopedTerminatorExitUnblocker exit_unblocker =
277 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700278 // Log every thousandth operation, and also the first and last ones
279 if ((next_operation_num_ % 1000 == 0) ||
280 (next_operation_num_ + 1 == total_operations)) {
281 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
282 << total_operations;
283 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700284 bool is_kernel_partition =
285 (next_operation_num_ >= manifest_.install_operations_size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700286 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
287 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700288 if (!PerformReplaceOperation(op, is_kernel_partition)) {
289 LOG(ERROR) << "Failed to perform replace operation "
290 << next_operation_num_;
Don Garrette410e0f2011-11-10 15:39:01 -0800291 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700292 }
293 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700294 if (!PerformMoveOperation(op, is_kernel_partition)) {
295 LOG(ERROR) << "Failed to perform move operation "
296 << next_operation_num_;
Don Garrette410e0f2011-11-10 15:39:01 -0800297 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700298 }
299 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700300 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
301 LOG(ERROR) << "Failed to perform bsdiff operation "
302 << next_operation_num_;
Don Garrette410e0f2011-11-10 15:39:01 -0800303 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700304 }
305 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700306 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700307 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700308 }
Don Garrette410e0f2011-11-10 15:39:01 -0800309 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700310}
311
312bool DeltaPerformer::CanPerformInstallOperation(
313 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
314 operation) {
315 // Move operations don't require any data blob, so they can always
316 // be performed
317 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
318 return true;
319
320 // See if we have the entire data blob in the buffer
321 if (operation.data_offset() < buffer_offset_) {
322 LOG(ERROR) << "we threw away data it seems?";
323 return false;
324 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700325
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700326 return (operation.data_offset() + operation.data_length()) <=
327 (buffer_offset_ + buffer_.size());
328}
329
330bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700331 const DeltaArchiveManifest_InstallOperation& operation,
332 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700333 CHECK(operation.type() == \
334 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
335 operation.type() == \
336 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
337
338 // Since we delete data off the beginning of the buffer as we use it,
339 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700340 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
341 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700342
Darin Petkov437adc42010-10-07 13:12:24 -0700343 // Extract the signature message if it's in this operation.
344 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700345
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700346 DirectExtentWriter direct_writer;
347 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
348 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700349
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700350 // Since bzip decompression is optional, we have a variable writer that will
351 // point to one of the ExtentWriter objects above.
352 ExtentWriter* writer = NULL;
353 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
354 writer = &zero_pad_writer;
355 } else if (operation.type() ==
356 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
357 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
358 writer = bzip_writer.get();
359 } else {
360 NOTREACHED();
361 }
362
363 // Create a vector of extents to pass to the ExtentWriter.
364 vector<Extent> extents;
365 for (int i = 0; i < operation.dst_extents_size(); i++) {
366 extents.push_back(operation.dst_extents(i));
367 }
368
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700369 int fd = is_kernel_partition ? kernel_fd_ : fd_;
370
371 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700372 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
373 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700374
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700375 // Update buffer
376 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700377 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700378 return true;
379}
380
381bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700382 const DeltaArchiveManifest_InstallOperation& operation,
383 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700384 // Calculate buffer size. Note, this function doesn't do a sliding
385 // window to copy in case the source and destination blocks overlap.
386 // If we wanted to do a sliding window, we could program the server
387 // to generate deltas that effectively did a sliding window.
388
389 uint64_t blocks_to_read = 0;
390 for (int i = 0; i < operation.src_extents_size(); i++)
391 blocks_to_read += operation.src_extents(i).num_blocks();
392
393 uint64_t blocks_to_write = 0;
394 for (int i = 0; i < operation.dst_extents_size(); i++)
395 blocks_to_write += operation.dst_extents(i).num_blocks();
396
397 DCHECK_EQ(blocks_to_write, blocks_to_read);
398 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700399
400 int fd = is_kernel_partition ? kernel_fd_ : fd_;
401
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700402 // Read in bytes.
403 ssize_t bytes_read = 0;
404 for (int i = 0; i < operation.src_extents_size(); i++) {
405 ssize_t bytes_read_this_iteration = 0;
406 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700407 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700408 &buf[bytes_read],
409 extent.num_blocks() * block_size_,
410 extent.start_block() * block_size_,
411 &bytes_read_this_iteration));
412 TEST_AND_RETURN_FALSE(
413 bytes_read_this_iteration ==
414 static_cast<ssize_t>(extent.num_blocks() * block_size_));
415 bytes_read += bytes_read_this_iteration;
416 }
417
Darin Petkov45580e42010-10-08 14:02:40 -0700418 // If this is a non-idempotent operation, request a delayed exit and clear the
419 // update state in case the operation gets interrupted. Do this as late as
420 // possible.
421 if (!IsIdempotentOperation(operation)) {
422 Terminator::set_exit_blocked(true);
423 ResetUpdateProgress(prefs_, true);
424 }
425
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700426 // Write bytes out.
427 ssize_t bytes_written = 0;
428 for (int i = 0; i < operation.dst_extents_size(); i++) {
429 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700430 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700431 &buf[bytes_written],
432 extent.num_blocks() * block_size_,
433 extent.start_block() * block_size_));
434 bytes_written += extent.num_blocks() * block_size_;
435 }
436 DCHECK_EQ(bytes_written, bytes_read);
437 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
438 return true;
439}
440
441bool DeltaPerformer::ExtentsToBsdiffPositionsString(
442 const RepeatedPtrField<Extent>& extents,
443 uint64_t block_size,
444 uint64_t full_length,
445 string* positions_string) {
446 string ret;
447 uint64_t length = 0;
448 for (int i = 0; i < extents.size(); i++) {
449 Extent extent = extents.Get(i);
450 int64_t start = extent.start_block();
451 uint64_t this_length = min(full_length - length,
452 extent.num_blocks() * block_size);
453 if (start == static_cast<int64_t>(kSparseHole))
454 start = -1;
455 else
456 start *= block_size;
457 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
458 length += this_length;
459 }
460 TEST_AND_RETURN_FALSE(length == full_length);
461 if (!ret.empty())
462 ret.resize(ret.size() - 1); // Strip trailing comma off
463 *positions_string = ret;
464 return true;
465}
466
467bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700468 const DeltaArchiveManifest_InstallOperation& operation,
469 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700470 // Since we delete data off the beginning of the buffer as we use it,
471 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700472 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
473 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700474
475 string input_positions;
476 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
477 block_size_,
478 operation.src_length(),
479 &input_positions));
480 string output_positions;
481 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
482 block_size_,
483 operation.dst_length(),
484 &output_positions));
485
486 string temp_filename;
487 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
488 &temp_filename,
489 NULL));
490 ScopedPathUnlinker path_unlinker(temp_filename);
491 {
492 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
493 ScopedFdCloser fd_closer(&fd);
494 TEST_AND_RETURN_FALSE(
495 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
496 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700497
498 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700499 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700500
Darin Petkov45580e42010-10-08 14:02:40 -0700501 // If this is a non-idempotent operation, request a delayed exit and clear the
502 // update state in case the operation gets interrupted. Do this as late as
503 // possible.
504 if (!IsIdempotentOperation(operation)) {
505 Terminator::set_exit_blocked(true);
506 ResetUpdateProgress(prefs_, true);
507 }
508
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700509 vector<string> cmd;
510 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700511 cmd.push_back(path);
512 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700513 cmd.push_back(temp_filename);
514 cmd.push_back(input_positions);
515 cmd.push_back(output_positions);
516 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700517 TEST_AND_RETURN_FALSE(
518 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700519 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700520 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700521 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700522 TEST_AND_RETURN_FALSE(return_code == 0);
523
524 if (operation.dst_length() % block_size_) {
525 // Zero out rest of final block.
526 // TODO(adlr): build this into bspatch; it's more efficient that way.
527 const Extent& last_extent =
528 operation.dst_extents(operation.dst_extents_size() - 1);
529 const uint64_t end_byte =
530 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
531 const uint64_t begin_byte =
532 end_byte - (block_size_ - operation.dst_length() % block_size_);
533 vector<char> zeros(end_byte - begin_byte);
534 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700535 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700536 }
537
538 // Update buffer.
539 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700540 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700541 return true;
542}
543
Darin Petkovd7061ab2010-10-06 14:37:09 -0700544bool DeltaPerformer::ExtractSignatureMessage(
545 const DeltaArchiveManifest_InstallOperation& operation) {
546 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
547 !manifest_.has_signatures_offset() ||
548 manifest_.signatures_offset() != operation.data_offset()) {
549 return false;
550 }
551 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
552 manifest_.signatures_size() == operation.data_length());
553 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
554 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
555 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700556 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700557 buffer_.begin(),
558 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700559
560 // Save the signature blob because if the update is interrupted after the
561 // download phase we don't go through this path anymore. Some alternatives to
562 // consider:
563 //
564 // 1. On resume, re-download the signature blob from the server and re-verify
565 // it.
566 //
567 // 2. Verify the signature as soon as it's received and don't checkpoint the
568 // blob and the signed sha-256 context.
569 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
570 string(&signatures_message_data_[0],
571 signatures_message_data_.size())))
572 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700573 // The hash of all data consumed so far should be verified against the signed
574 // hash.
575 signed_hash_context_ = hash_calculator_.GetContext();
576 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
577 signed_hash_context_))
578 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700579 LOG(INFO) << "Extracted signature data of size "
580 << manifest_.signatures_size() << " at "
581 << manifest_.signatures_offset();
582 return true;
583}
584
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700585#define TEST_AND_RETURN_VAL(_retval, _condition) \
586 do { \
587 if (!(_condition)) { \
588 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
589 return _retval; \
590 } \
591 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700592
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700593
594ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700595 const string& public_key_path,
596 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700597 const uint64_t update_check_response_size) {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700598 string key_path = public_key_path;
599 if (key_path.empty()) {
600 key_path = kUpdatePayloadPublicKeyPath;
601 }
602 LOG(INFO) << "Verifying delta payload. Public key path: " << key_path;
Darin Petkov437adc42010-10-07 13:12:24 -0700603
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700604 // Verifies the download size.
605 TEST_AND_RETURN_VAL(kActionCodeDownloadSizeMismatchError,
606 update_check_response_size ==
607 manifest_metadata_size_ + buffer_offset_);
608
Darin Petkov437adc42010-10-07 13:12:24 -0700609 // Verifies the download hash.
610 const string& download_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700611 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
612 !download_hash_data.empty());
Darin Petkov7ed561b2011-10-04 02:59:03 -0700613 TEST_AND_RETURN_VAL(kActionCodeDownloadHashMismatchError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700614 download_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700615
Darin Petkov437adc42010-10-07 13:12:24 -0700616 // Verifies the signed payload hash.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700617 if (!utils::FileExists(key_path.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700618 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700619 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700620 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700621 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
622 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700623 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700624 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
625 PayloadSigner::VerifySignature(
626 signatures_message_data_,
627 key_path,
628 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700629 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700630 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
631 signed_hasher.SetContext(signed_hash_context_));
632 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
633 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700634 vector<char> hash_data = signed_hasher.raw_hash();
635 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700636 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
637 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700638 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700639 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700640 "Attached Signature:";
641 utils::HexDumpVector(signed_hash_data);
642 LOG(ERROR) << "Computed Signature:";
643 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700644 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700645 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700646 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700647}
648
Darin Petkov3aefa862010-12-07 14:45:00 -0800649bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
650 vector<char>* kernel_hash,
651 uint64_t* rootfs_size,
652 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700653 TEST_AND_RETURN_FALSE(manifest_valid_ &&
654 manifest_.has_new_kernel_info() &&
655 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800656 *kernel_size = manifest_.new_kernel_info().size();
657 *rootfs_size = manifest_.new_rootfs_info().size();
658 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
659 manifest_.new_kernel_info().hash().end());
660 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
661 manifest_.new_rootfs_info().hash().end());
662 kernel_hash->swap(new_kernel_hash);
663 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700664 return true;
665}
666
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700667namespace {
668void LogVerifyError(bool is_kern,
669 const string& local_hash,
670 const string& expected_hash) {
671 const char* type = is_kern ? "kernel" : "rootfs";
672 LOG(ERROR) << "This is a server-side error due to "
673 << "mismatched delta update image!";
674 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
675 << "update that must be applied over a " << type << " with "
676 << "a specific checksum, but the " << type << " we're starting "
677 << "with doesn't have that checksum! This means that "
678 << "the delta I've been given doesn't match my existing "
679 << "system. The " << type << " partition I have has hash: "
680 << local_hash << " but the update expected me to have "
681 << expected_hash << " .";
682 if (is_kern) {
683 LOG(INFO) << "To get the checksum of a kernel partition on a "
684 << "booted machine, run this command (change /dev/sda2 "
685 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
686 << "openssl dgst -sha256 -binary | openssl base64";
687 } else {
688 LOG(INFO) << "To get the checksum of a rootfs partition on a "
689 << "booted machine, run this command (change /dev/sda3 "
690 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
691 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
692 << "| sed 's/[^0-9]*//') / 256 )) | "
693 << "openssl dgst -sha256 -binary | openssl base64";
694 }
695 LOG(INFO) << "To get the checksum of partitions in a bin file, "
696 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
697}
698
699string StringForHashBytes(const void* bytes, size_t size) {
700 string ret;
701 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
702 ret = "<unknown>";
703 }
704 return ret;
705}
706} // namespace
707
Darin Petkov698d0412010-10-13 10:59:44 -0700708bool DeltaPerformer::VerifySourcePartitions() {
709 LOG(INFO) << "Verifying source partitions.";
710 CHECK(manifest_valid_);
711 if (manifest_.has_old_kernel_info()) {
712 const PartitionInfo& info = manifest_.old_kernel_info();
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700713 bool valid = !current_kernel_hash_.empty() &&
714 current_kernel_hash_.size() == info.hash().size() &&
715 memcmp(current_kernel_hash_.data(),
716 info.hash().data(),
717 current_kernel_hash_.size()) == 0;
718 if (!valid) {
719 LogVerifyError(true,
720 StringForHashBytes(current_kernel_hash_.data(),
721 current_kernel_hash_.size()),
722 StringForHashBytes(info.hash().data(),
723 info.hash().size()));
724 }
725 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700726 }
727 if (manifest_.has_old_rootfs_info()) {
728 const PartitionInfo& info = manifest_.old_rootfs_info();
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700729 bool valid = !current_rootfs_hash_.empty() &&
730 current_rootfs_hash_.size() == info.hash().size() &&
731 memcmp(current_rootfs_hash_.data(),
732 info.hash().data(),
733 current_rootfs_hash_.size()) == 0;
734 if (!valid) {
735 LogVerifyError(false,
736 StringForHashBytes(current_kernel_hash_.data(),
737 current_kernel_hash_.size()),
738 StringForHashBytes(info.hash().data(),
739 info.hash().size()));
740 }
741 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700742 }
743 return true;
744}
745
Darin Petkov437adc42010-10-07 13:12:24 -0700746void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
747 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700748 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
749}
750
Darin Petkov0406e402010-10-06 21:33:11 -0700751bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
752 string update_check_response_hash) {
753 int64_t next_operation = kUpdateStateOperationInvalid;
754 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
755 &next_operation) &&
756 next_operation != kUpdateStateOperationInvalid &&
757 next_operation > 0);
758
759 string interrupted_hash;
760 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
761 &interrupted_hash) &&
762 !interrupted_hash.empty() &&
763 interrupted_hash == update_check_response_hash);
764
Darin Petkov61426142010-10-08 11:04:55 -0700765 int64_t resumed_update_failures;
766 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
767 &resumed_update_failures) ||
768 resumed_update_failures <= kMaxResumedUpdateFailures);
769
Darin Petkov0406e402010-10-06 21:33:11 -0700770 // Sanity check the rest.
771 int64_t next_data_offset = -1;
772 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
773 &next_data_offset) &&
774 next_data_offset >= 0);
775
Darin Petkov437adc42010-10-07 13:12:24 -0700776 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700777 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700778 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
779 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700780
781 int64_t manifest_metadata_size = 0;
782 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
783 &manifest_metadata_size) &&
784 manifest_metadata_size > 0);
785
786 return true;
787}
788
Darin Petkov9b230572010-10-08 10:20:09 -0700789bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -0700790 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
791 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -0700792 if (!quick) {
793 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
794 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
795 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
796 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700797 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -0700798 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -0700799 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -0700800 }
Darin Petkov73058b42010-10-06 16:32:19 -0700801 return true;
802}
803
804bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700805 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -0700806 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700807 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -0700808 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -0700809 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700810 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -0700811 hash_calculator_.GetContext()));
812 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
813 buffer_offset_));
814 last_updated_buffer_offset_ = buffer_offset_;
815 }
Darin Petkov73058b42010-10-06 16:32:19 -0700816 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
817 next_operation_num_));
818 return true;
819}
820
Darin Petkov9b230572010-10-08 10:20:09 -0700821bool DeltaPerformer::PrimeUpdateState() {
822 CHECK(manifest_valid_);
823 block_size_ = manifest_.block_size();
824
825 int64_t next_operation = kUpdateStateOperationInvalid;
826 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
827 next_operation == kUpdateStateOperationInvalid ||
828 next_operation <= 0) {
829 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -0700830 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -0700831 return true;
832 }
833 next_operation_num_ = next_operation;
834
835 // Resuming an update -- load the rest of the update state.
836 int64_t next_data_offset = -1;
837 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
838 &next_data_offset) &&
839 next_data_offset >= 0);
840 buffer_offset_ = next_data_offset;
841
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700842 // The signed hash context and the signature blob may be empty if the
843 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -0700844 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
845 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700846 string signature_blob;
847 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
848 signatures_message_data_.assign(signature_blob.begin(),
849 signature_blob.end());
850 }
Darin Petkov9b230572010-10-08 10:20:09 -0700851
852 string hash_context;
853 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
854 &hash_context) &&
855 hash_calculator_.SetContext(hash_context));
856
857 int64_t manifest_metadata_size = 0;
858 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
859 &manifest_metadata_size) &&
860 manifest_metadata_size > 0);
861 manifest_metadata_size_ = manifest_metadata_size;
862
Darin Petkov61426142010-10-08 11:04:55 -0700863 // Speculatively count the resume as a failure.
864 int64_t resumed_update_failures;
865 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
866 resumed_update_failures++;
867 } else {
868 resumed_update_failures = 1;
869 }
870 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -0700871 return true;
872}
873
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700874} // namespace chromeos_update_engine