blob: 66c23d405dac7f5349f32b07f1cad1f9d155c065 [file] [log] [blame]
Darin Petkov85d02b72011-05-17 13:25:51 -07001// Copyright (c) 2011 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>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070017#include <google/protobuf/repeated_field.h>
18
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019#include "update_engine/bzip_extent_writer.h"
20#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070021#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include "update_engine/extent_writer.h"
23#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070024#include "update_engine/payload_signer.h"
Darin Petkov73058b42010-10-06 16:32:19 -070025#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070027#include "update_engine/terminator.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070028
29using std::min;
30using std::string;
31using std::vector;
32using google::protobuf::RepeatedPtrField;
33
34namespace chromeos_update_engine {
35
Darin Petkovabc7bc02011-02-23 14:39:43 -080036const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
37 "/usr/share/update_engine/update-payload-key.pub.pem";
38
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070039namespace {
40
41const int kDeltaVersionLength = 8;
42const int kDeltaProtobufLengthLength = 8;
Darin Petkov73058b42010-10-06 16:32:19 -070043const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070044const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070045
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070046// Converts extents to a human-readable string, for use by DumpUpdateProto().
47string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
48 string ret;
49 for (int i = 0; i < extents.size(); i++) {
50 const Extent& extent = extents.Get(i);
51 if (extent.start_block() == kSparseHole) {
52 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
53 } else {
54 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
55 extent.start_block(), extent.num_blocks());
56 }
57 }
58 if (!ret.empty()) {
59 DCHECK_GT(ret.size(), static_cast<size_t>(1));
60 ret.resize(ret.size() - 2);
61 }
62 return ret;
63}
64
65// LOGs a DeltaArchiveManifest object. Useful for debugging.
66void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
67 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070068 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070069 for (int i = 0; i < (manifest.install_operations_size() +
70 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070071 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070072 i < manifest.install_operations_size() ?
73 manifest.install_operations(i) :
74 manifest.kernel_install_operations(
75 i - manifest.install_operations_size());
76 if (i == 0)
77 LOG(INFO) << " Rootfs ops:";
78 else if (i == manifest.install_operations_size())
79 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070080 LOG(INFO) << " operation(" << i << ")";
81 LOG(INFO) << " type: "
82 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
83 if (op.has_data_offset())
84 LOG(INFO) << " data_offset: " << op.data_offset();
85 if (op.has_data_length())
86 LOG(INFO) << " data_length: " << op.data_length();
87 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
88 if (op.has_src_length())
89 LOG(INFO) << " src_length: " << op.src_length();
90 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
91 if (op.has_dst_length())
92 LOG(INFO) << " dst_length: " << op.dst_length();
93 }
94}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070095
96// Opens path for read/write, put the fd into *fd. On success returns true
97// and sets *err to 0. On failure, returns false and sets *err to errno.
98bool OpenFile(const char* path, int* fd, int* err) {
99 if (*fd != -1) {
100 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
101 *err = EINVAL;
102 return false;
103 }
104 *fd = open(path, O_RDWR, 000);
105 if (*fd < 0) {
106 *err = errno;
107 PLOG(ERROR) << "Unable to open file " << path;
108 return false;
109 }
110 *err = 0;
111 return true;
112}
113
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700114} // namespace {}
115
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700116// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
117// it safely. Returns false otherwise.
118bool DeltaPerformer::IsIdempotentOperation(
119 const DeltaArchiveManifest_InstallOperation& op) {
120 if (op.src_extents_size() == 0) {
121 return true;
122 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700123 // When in doubt, it's safe to declare an op non-idempotent. Note that we
124 // could detect other types of idempotent operations here such as a MOVE that
125 // moves blocks onto themselves. However, we rely on the server to not send
126 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700127 ExtentRanges src_ranges;
128 src_ranges.AddRepeatedExtents(op.src_extents());
129 const uint64_t block_count = src_ranges.blocks();
130 src_ranges.SubtractRepeatedExtents(op.dst_extents());
131 return block_count == src_ranges.blocks();
132}
133
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700134int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700135 int err;
136 if (OpenFile(path, &fd_, &err))
137 path_ = path;
138 return -err;
139}
140
141bool DeltaPerformer::OpenKernel(const char* kernel_path) {
142 int err;
143 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
144 if (success)
145 kernel_path_ = kernel_path;
146 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700147}
148
149int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700150 int err = 0;
151 if (close(kernel_fd_) == -1) {
152 err = errno;
153 PLOG(ERROR) << "Unable to close kernel fd:";
154 }
155 if (close(fd_) == -1) {
156 err = errno;
157 PLOG(ERROR) << "Unable to close rootfs fd:";
158 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700159 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800160 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700161 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800162 if (!buffer_.empty()) {
163 LOG(ERROR) << "Called Close() while buffer not empty!";
164 if (err >= 0) {
165 err = 1;
166 }
167 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700168 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700169}
170
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700171namespace {
172
173void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
174 string sha256;
175 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
176 info.hash().size(),
177 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800178 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
179 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700180 } else {
181 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
182 }
183}
184
185void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
186 if (manifest.has_old_kernel_info())
187 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
188 if (manifest.has_old_rootfs_info())
189 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
190 if (manifest.has_new_kernel_info())
191 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
192 if (manifest.has_new_rootfs_info())
193 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
194}
195
196} // namespace {}
197
Darin Petkov9574f7e2011-01-13 10:48:12 -0800198DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
199 const std::vector<char>& payload,
200 DeltaArchiveManifest* manifest,
201 uint64_t* metadata_size) {
202 if (payload.size() < strlen(kDeltaMagic) +
203 kDeltaVersionLength + kDeltaProtobufLengthLength) {
204 // Don't have enough bytes to know the protobuf length.
205 return kMetadataParseInsufficientData;
206 }
207 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
208 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
209 return kMetadataParseError;
210 }
211 uint64_t protobuf_length;
212 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
213 protobuf_length_size_mismatch);
214 memcpy(&protobuf_length,
215 &payload[strlen(kDeltaMagic) + kDeltaVersionLength],
216 kDeltaProtobufLengthLength);
217 protobuf_length = be64toh(protobuf_length); // switch big endian to host
218 if (payload.size() < strlen(kDeltaMagic) + kDeltaVersionLength +
219 kDeltaProtobufLengthLength + protobuf_length) {
220 return kMetadataParseInsufficientData;
221 }
222 // We have the full proto buffer in |payload|. Parse it.
223 const int offset = strlen(kDeltaMagic) + kDeltaVersionLength +
224 kDeltaProtobufLengthLength;
225 if (!manifest->ParseFromArray(&payload[offset], protobuf_length)) {
226 LOG(ERROR) << "Unable to parse manifest in update file.";
227 return kMetadataParseError;
228 }
229 *metadata_size = strlen(kDeltaMagic) + kDeltaVersionLength +
230 kDeltaProtobufLengthLength + protobuf_length;
231 return kMetadataParseSuccess;
232}
233
234
Don Garrette410e0f2011-11-10 15:39:01 -0800235// Wrapper around write. Returns true if all requested bytes
236// were written, or false on any error, reguardless of progress.
237bool DeltaPerformer::Write(const void* bytes, size_t count) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700238 const char* c_bytes = reinterpret_cast<const char*>(bytes);
239 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
240
241 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800242 MetadataParseResult result = ParsePayloadMetadata(buffer_,
243 &manifest_,
244 &manifest_metadata_size_);
245 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800246 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800247 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800248 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800249 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700250 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700251 // Remove protobuf and header info from buffer_, so buffer_ contains
252 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700253 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700254 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700255 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700256 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700257 manifest_valid_ = true;
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700258 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700259 if (!PrimeUpdateState()) {
260 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800261 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700262 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700263 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700264 ssize_t total_operations = manifest_.install_operations_size() +
265 manifest_.kernel_install_operations_size();
266 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700267 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700268 next_operation_num_ < manifest_.install_operations_size() ?
269 manifest_.install_operations(next_operation_num_) :
270 manifest_.kernel_install_operations(
271 next_operation_num_ - manifest_.install_operations_size());
272 if (!CanPerformInstallOperation(op))
273 break;
Darin Petkov45580e42010-10-08 14:02:40 -0700274 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700275 ScopedTerminatorExitUnblocker exit_unblocker =
276 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700277 // Log every thousandth operation, and also the first and last ones
278 if ((next_operation_num_ % 1000 == 0) ||
279 (next_operation_num_ + 1 == total_operations)) {
280 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
281 << total_operations;
282 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700283 bool is_kernel_partition =
284 (next_operation_num_ >= manifest_.install_operations_size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700285 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
286 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700287 if (!PerformReplaceOperation(op, is_kernel_partition)) {
288 LOG(ERROR) << "Failed to perform replace operation "
289 << next_operation_num_;
Don Garrette410e0f2011-11-10 15:39:01 -0800290 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700291 }
292 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700293 if (!PerformMoveOperation(op, is_kernel_partition)) {
294 LOG(ERROR) << "Failed to perform move operation "
295 << next_operation_num_;
Don Garrette410e0f2011-11-10 15:39:01 -0800296 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700297 }
298 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700299 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
300 LOG(ERROR) << "Failed to perform bsdiff operation "
301 << next_operation_num_;
Don Garrette410e0f2011-11-10 15:39:01 -0800302 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700303 }
304 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700305 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700306 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700307 }
Don Garrette410e0f2011-11-10 15:39:01 -0800308 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700309}
310
311bool DeltaPerformer::CanPerformInstallOperation(
312 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
313 operation) {
314 // Move operations don't require any data blob, so they can always
315 // be performed
316 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
317 return true;
318
319 // See if we have the entire data blob in the buffer
320 if (operation.data_offset() < buffer_offset_) {
321 LOG(ERROR) << "we threw away data it seems?";
322 return false;
323 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700324
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700325 return (operation.data_offset() + operation.data_length()) <=
326 (buffer_offset_ + buffer_.size());
327}
328
329bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700330 const DeltaArchiveManifest_InstallOperation& operation,
331 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700332 CHECK(operation.type() == \
333 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
334 operation.type() == \
335 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
336
337 // Since we delete data off the beginning of the buffer as we use it,
338 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700339 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
340 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700341
Darin Petkov437adc42010-10-07 13:12:24 -0700342 // Extract the signature message if it's in this operation.
343 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700344
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700345 DirectExtentWriter direct_writer;
346 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
347 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700348
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700349 // Since bzip decompression is optional, we have a variable writer that will
350 // point to one of the ExtentWriter objects above.
351 ExtentWriter* writer = NULL;
352 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
353 writer = &zero_pad_writer;
354 } else if (operation.type() ==
355 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
356 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
357 writer = bzip_writer.get();
358 } else {
359 NOTREACHED();
360 }
361
362 // Create a vector of extents to pass to the ExtentWriter.
363 vector<Extent> extents;
364 for (int i = 0; i < operation.dst_extents_size(); i++) {
365 extents.push_back(operation.dst_extents(i));
366 }
367
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700368 int fd = is_kernel_partition ? kernel_fd_ : fd_;
369
370 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700371 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
372 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700373
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700374 // Update buffer
375 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700376 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700377 return true;
378}
379
380bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700381 const DeltaArchiveManifest_InstallOperation& operation,
382 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700383 // Calculate buffer size. Note, this function doesn't do a sliding
384 // window to copy in case the source and destination blocks overlap.
385 // If we wanted to do a sliding window, we could program the server
386 // to generate deltas that effectively did a sliding window.
387
388 uint64_t blocks_to_read = 0;
389 for (int i = 0; i < operation.src_extents_size(); i++)
390 blocks_to_read += operation.src_extents(i).num_blocks();
391
392 uint64_t blocks_to_write = 0;
393 for (int i = 0; i < operation.dst_extents_size(); i++)
394 blocks_to_write += operation.dst_extents(i).num_blocks();
395
396 DCHECK_EQ(blocks_to_write, blocks_to_read);
397 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700398
399 int fd = is_kernel_partition ? kernel_fd_ : fd_;
400
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700401 // Read in bytes.
402 ssize_t bytes_read = 0;
403 for (int i = 0; i < operation.src_extents_size(); i++) {
404 ssize_t bytes_read_this_iteration = 0;
405 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700406 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700407 &buf[bytes_read],
408 extent.num_blocks() * block_size_,
409 extent.start_block() * block_size_,
410 &bytes_read_this_iteration));
411 TEST_AND_RETURN_FALSE(
412 bytes_read_this_iteration ==
413 static_cast<ssize_t>(extent.num_blocks() * block_size_));
414 bytes_read += bytes_read_this_iteration;
415 }
416
Darin Petkov45580e42010-10-08 14:02:40 -0700417 // If this is a non-idempotent operation, request a delayed exit and clear the
418 // update state in case the operation gets interrupted. Do this as late as
419 // possible.
420 if (!IsIdempotentOperation(operation)) {
421 Terminator::set_exit_blocked(true);
422 ResetUpdateProgress(prefs_, true);
423 }
424
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700425 // Write bytes out.
426 ssize_t bytes_written = 0;
427 for (int i = 0; i < operation.dst_extents_size(); i++) {
428 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700429 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700430 &buf[bytes_written],
431 extent.num_blocks() * block_size_,
432 extent.start_block() * block_size_));
433 bytes_written += extent.num_blocks() * block_size_;
434 }
435 DCHECK_EQ(bytes_written, bytes_read);
436 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
437 return true;
438}
439
440bool DeltaPerformer::ExtentsToBsdiffPositionsString(
441 const RepeatedPtrField<Extent>& extents,
442 uint64_t block_size,
443 uint64_t full_length,
444 string* positions_string) {
445 string ret;
446 uint64_t length = 0;
447 for (int i = 0; i < extents.size(); i++) {
448 Extent extent = extents.Get(i);
449 int64_t start = extent.start_block();
450 uint64_t this_length = min(full_length - length,
451 extent.num_blocks() * block_size);
452 if (start == static_cast<int64_t>(kSparseHole))
453 start = -1;
454 else
455 start *= block_size;
456 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
457 length += this_length;
458 }
459 TEST_AND_RETURN_FALSE(length == full_length);
460 if (!ret.empty())
461 ret.resize(ret.size() - 1); // Strip trailing comma off
462 *positions_string = ret;
463 return true;
464}
465
466bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700467 const DeltaArchiveManifest_InstallOperation& operation,
468 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700469 // Since we delete data off the beginning of the buffer as we use it,
470 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700471 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
472 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700473
474 string input_positions;
475 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
476 block_size_,
477 operation.src_length(),
478 &input_positions));
479 string output_positions;
480 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
481 block_size_,
482 operation.dst_length(),
483 &output_positions));
484
485 string temp_filename;
486 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
487 &temp_filename,
488 NULL));
489 ScopedPathUnlinker path_unlinker(temp_filename);
490 {
491 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
492 ScopedFdCloser fd_closer(&fd);
493 TEST_AND_RETURN_FALSE(
494 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
495 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700496
497 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700498 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700499
Darin Petkov45580e42010-10-08 14:02:40 -0700500 // If this is a non-idempotent operation, request a delayed exit and clear the
501 // update state in case the operation gets interrupted. Do this as late as
502 // possible.
503 if (!IsIdempotentOperation(operation)) {
504 Terminator::set_exit_blocked(true);
505 ResetUpdateProgress(prefs_, true);
506 }
507
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700508 vector<string> cmd;
509 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700510 cmd.push_back(path);
511 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700512 cmd.push_back(temp_filename);
513 cmd.push_back(input_positions);
514 cmd.push_back(output_positions);
515 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700516 TEST_AND_RETURN_FALSE(
517 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700518 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700519 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700520 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700521 TEST_AND_RETURN_FALSE(return_code == 0);
522
523 if (operation.dst_length() % block_size_) {
524 // Zero out rest of final block.
525 // TODO(adlr): build this into bspatch; it's more efficient that way.
526 const Extent& last_extent =
527 operation.dst_extents(operation.dst_extents_size() - 1);
528 const uint64_t end_byte =
529 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
530 const uint64_t begin_byte =
531 end_byte - (block_size_ - operation.dst_length() % block_size_);
532 vector<char> zeros(end_byte - begin_byte);
533 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700534 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700535 }
536
537 // Update buffer.
538 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700539 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700540 return true;
541}
542
Darin Petkovd7061ab2010-10-06 14:37:09 -0700543bool DeltaPerformer::ExtractSignatureMessage(
544 const DeltaArchiveManifest_InstallOperation& operation) {
545 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
546 !manifest_.has_signatures_offset() ||
547 manifest_.signatures_offset() != operation.data_offset()) {
548 return false;
549 }
550 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
551 manifest_.signatures_size() == operation.data_length());
552 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
553 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
554 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700555 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700556 buffer_.begin(),
557 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700558
559 // Save the signature blob because if the update is interrupted after the
560 // download phase we don't go through this path anymore. Some alternatives to
561 // consider:
562 //
563 // 1. On resume, re-download the signature blob from the server and re-verify
564 // it.
565 //
566 // 2. Verify the signature as soon as it's received and don't checkpoint the
567 // blob and the signed sha-256 context.
568 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
569 string(&signatures_message_data_[0],
570 signatures_message_data_.size())))
571 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700572 // The hash of all data consumed so far should be verified against the signed
573 // hash.
574 signed_hash_context_ = hash_calculator_.GetContext();
575 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
576 signed_hash_context_))
577 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700578 LOG(INFO) << "Extracted signature data of size "
579 << manifest_.signatures_size() << " at "
580 << manifest_.signatures_offset();
581 return true;
582}
583
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700584#define TEST_AND_RETURN_VAL(_retval, _condition) \
585 do { \
586 if (!(_condition)) { \
587 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
588 return _retval; \
589 } \
590 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700591
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700592
593ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700594 const string& public_key_path,
595 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700596 const uint64_t update_check_response_size) {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700597 string key_path = public_key_path;
598 if (key_path.empty()) {
599 key_path = kUpdatePayloadPublicKeyPath;
600 }
601 LOG(INFO) << "Verifying delta payload. Public key path: " << key_path;
Darin Petkov437adc42010-10-07 13:12:24 -0700602
603 // Verifies the download hash.
604 const string& download_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700605 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
606 !download_hash_data.empty());
Darin Petkov7ed561b2011-10-04 02:59:03 -0700607 TEST_AND_RETURN_VAL(kActionCodeDownloadHashMismatchError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700608 download_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700609
610 // Verifies the download size.
Darin Petkov7ed561b2011-10-04 02:59:03 -0700611 TEST_AND_RETURN_VAL(kActionCodeDownloadSizeMismatchError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700612 update_check_response_size ==
613 manifest_metadata_size_ + buffer_offset_);
Darin Petkov437adc42010-10-07 13:12:24 -0700614
615 // Verifies the signed payload hash.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700616 if (!utils::FileExists(key_path.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700617 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700618 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700619 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700620 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
621 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700622 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700623 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
624 PayloadSigner::VerifySignature(
625 signatures_message_data_,
626 key_path,
627 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700628 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700629 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
630 signed_hasher.SetContext(signed_hash_context_));
631 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
632 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700633 vector<char> hash_data = signed_hasher.raw_hash();
634 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700635 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
636 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700637 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700638 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700639 "Attached Signature:";
640 utils::HexDumpVector(signed_hash_data);
641 LOG(ERROR) << "Computed Signature:";
642 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700643 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700644 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700645 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700646}
647
Darin Petkov3aefa862010-12-07 14:45:00 -0800648bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
649 vector<char>* kernel_hash,
650 uint64_t* rootfs_size,
651 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700652 TEST_AND_RETURN_FALSE(manifest_valid_ &&
653 manifest_.has_new_kernel_info() &&
654 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800655 *kernel_size = manifest_.new_kernel_info().size();
656 *rootfs_size = manifest_.new_rootfs_info().size();
657 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
658 manifest_.new_kernel_info().hash().end());
659 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
660 manifest_.new_rootfs_info().hash().end());
661 kernel_hash->swap(new_kernel_hash);
662 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700663 return true;
664}
665
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700666namespace {
667void LogVerifyError(bool is_kern,
668 const string& local_hash,
669 const string& expected_hash) {
670 const char* type = is_kern ? "kernel" : "rootfs";
671 LOG(ERROR) << "This is a server-side error due to "
672 << "mismatched delta update image!";
673 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
674 << "update that must be applied over a " << type << " with "
675 << "a specific checksum, but the " << type << " we're starting "
676 << "with doesn't have that checksum! This means that "
677 << "the delta I've been given doesn't match my existing "
678 << "system. The " << type << " partition I have has hash: "
679 << local_hash << " but the update expected me to have "
680 << expected_hash << " .";
681 if (is_kern) {
682 LOG(INFO) << "To get the checksum of a kernel partition on a "
683 << "booted machine, run this command (change /dev/sda2 "
684 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
685 << "openssl dgst -sha256 -binary | openssl base64";
686 } else {
687 LOG(INFO) << "To get the checksum of a rootfs partition on a "
688 << "booted machine, run this command (change /dev/sda3 "
689 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
690 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
691 << "| sed 's/[^0-9]*//') / 256 )) | "
692 << "openssl dgst -sha256 -binary | openssl base64";
693 }
694 LOG(INFO) << "To get the checksum of partitions in a bin file, "
695 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
696}
697
698string StringForHashBytes(const void* bytes, size_t size) {
699 string ret;
700 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
701 ret = "<unknown>";
702 }
703 return ret;
704}
705} // namespace
706
Darin Petkov698d0412010-10-13 10:59:44 -0700707bool DeltaPerformer::VerifySourcePartitions() {
708 LOG(INFO) << "Verifying source partitions.";
709 CHECK(manifest_valid_);
710 if (manifest_.has_old_kernel_info()) {
711 const PartitionInfo& info = manifest_.old_kernel_info();
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700712 bool valid = !current_kernel_hash_.empty() &&
713 current_kernel_hash_.size() == info.hash().size() &&
714 memcmp(current_kernel_hash_.data(),
715 info.hash().data(),
716 current_kernel_hash_.size()) == 0;
717 if (!valid) {
718 LogVerifyError(true,
719 StringForHashBytes(current_kernel_hash_.data(),
720 current_kernel_hash_.size()),
721 StringForHashBytes(info.hash().data(),
722 info.hash().size()));
723 }
724 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700725 }
726 if (manifest_.has_old_rootfs_info()) {
727 const PartitionInfo& info = manifest_.old_rootfs_info();
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700728 bool valid = !current_rootfs_hash_.empty() &&
729 current_rootfs_hash_.size() == info.hash().size() &&
730 memcmp(current_rootfs_hash_.data(),
731 info.hash().data(),
732 current_rootfs_hash_.size()) == 0;
733 if (!valid) {
734 LogVerifyError(false,
735 StringForHashBytes(current_kernel_hash_.data(),
736 current_kernel_hash_.size()),
737 StringForHashBytes(info.hash().data(),
738 info.hash().size()));
739 }
740 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -0700741 }
742 return true;
743}
744
Darin Petkov437adc42010-10-07 13:12:24 -0700745void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
746 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700747 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
748}
749
Darin Petkov0406e402010-10-06 21:33:11 -0700750bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
751 string update_check_response_hash) {
752 int64_t next_operation = kUpdateStateOperationInvalid;
753 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
754 &next_operation) &&
755 next_operation != kUpdateStateOperationInvalid &&
756 next_operation > 0);
757
758 string interrupted_hash;
759 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
760 &interrupted_hash) &&
761 !interrupted_hash.empty() &&
762 interrupted_hash == update_check_response_hash);
763
Darin Petkov61426142010-10-08 11:04:55 -0700764 int64_t resumed_update_failures;
765 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
766 &resumed_update_failures) ||
767 resumed_update_failures <= kMaxResumedUpdateFailures);
768
Darin Petkov0406e402010-10-06 21:33:11 -0700769 // Sanity check the rest.
770 int64_t next_data_offset = -1;
771 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
772 &next_data_offset) &&
773 next_data_offset >= 0);
774
Darin Petkov437adc42010-10-07 13:12:24 -0700775 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700776 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700777 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
778 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700779
780 int64_t manifest_metadata_size = 0;
781 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
782 &manifest_metadata_size) &&
783 manifest_metadata_size > 0);
784
785 return true;
786}
787
Darin Petkov9b230572010-10-08 10:20:09 -0700788bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -0700789 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
790 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -0700791 if (!quick) {
792 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
793 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
794 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
795 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700796 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -0700797 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -0700798 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -0700799 }
Darin Petkov73058b42010-10-06 16:32:19 -0700800 return true;
801}
802
803bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700804 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -0700805 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700806 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -0700807 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -0700808 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700809 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -0700810 hash_calculator_.GetContext()));
811 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
812 buffer_offset_));
813 last_updated_buffer_offset_ = buffer_offset_;
814 }
Darin Petkov73058b42010-10-06 16:32:19 -0700815 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
816 next_operation_num_));
817 return true;
818}
819
Darin Petkov9b230572010-10-08 10:20:09 -0700820bool DeltaPerformer::PrimeUpdateState() {
821 CHECK(manifest_valid_);
822 block_size_ = manifest_.block_size();
823
824 int64_t next_operation = kUpdateStateOperationInvalid;
825 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
826 next_operation == kUpdateStateOperationInvalid ||
827 next_operation <= 0) {
828 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -0700829 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -0700830 return true;
831 }
832 next_operation_num_ = next_operation;
833
834 // Resuming an update -- load the rest of the update state.
835 int64_t next_data_offset = -1;
836 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
837 &next_data_offset) &&
838 next_data_offset >= 0);
839 buffer_offset_ = next_data_offset;
840
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700841 // The signed hash context and the signature blob may be empty if the
842 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -0700843 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
844 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700845 string signature_blob;
846 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
847 signatures_message_data_.assign(signature_blob.begin(),
848 signature_blob.end());
849 }
Darin Petkov9b230572010-10-08 10:20:09 -0700850
851 string hash_context;
852 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
853 &hash_context) &&
854 hash_calculator_.SetContext(hash_context));
855
856 int64_t manifest_metadata_size = 0;
857 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
858 &manifest_metadata_size) &&
859 manifest_metadata_size > 0);
860 manifest_metadata_size_ = manifest_metadata_size;
861
Darin Petkov61426142010-10-08 11:04:55 -0700862 // Speculatively count the resume as a failure.
863 int64_t resumed_update_failures;
864 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
865 resumed_update_failures++;
866 } else {
867 resumed_update_failures = 1;
868 }
869 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -0700870 return true;
871}
872
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700873} // namespace chromeos_update_engine