blob: 8fc479b7d3d98993f14c37dd2163acdcaee57e2e [file] [log] [blame]
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2// 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
Darin Petkovd7061ab2010-10-06 14:37:09 -070015#include <base/scoped_ptr.h>
16#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
36namespace {
37
38const int kDeltaVersionLength = 8;
39const int kDeltaProtobufLengthLength = 8;
Darin Petkovd7061ab2010-10-06 14:37:09 -070040const char kUpdatePayloadPublicKeyPath[] =
41 "/usr/share/update_engine/update-payload-key.pub.pem";
Darin Petkov73058b42010-10-06 16:32:19 -070042const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070043const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070044
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070045// Converts extents to a human-readable string, for use by DumpUpdateProto().
46string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
47 string ret;
48 for (int i = 0; i < extents.size(); i++) {
49 const Extent& extent = extents.Get(i);
50 if (extent.start_block() == kSparseHole) {
51 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
52 } else {
53 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
54 extent.start_block(), extent.num_blocks());
55 }
56 }
57 if (!ret.empty()) {
58 DCHECK_GT(ret.size(), static_cast<size_t>(1));
59 ret.resize(ret.size() - 2);
60 }
61 return ret;
62}
63
64// LOGs a DeltaArchiveManifest object. Useful for debugging.
65void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
66 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070067 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070068 for (int i = 0; i < (manifest.install_operations_size() +
69 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070070 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070071 i < manifest.install_operations_size() ?
72 manifest.install_operations(i) :
73 manifest.kernel_install_operations(
74 i - manifest.install_operations_size());
75 if (i == 0)
76 LOG(INFO) << " Rootfs ops:";
77 else if (i == manifest.install_operations_size())
78 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079 LOG(INFO) << " operation(" << i << ")";
80 LOG(INFO) << " type: "
81 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
82 if (op.has_data_offset())
83 LOG(INFO) << " data_offset: " << op.data_offset();
84 if (op.has_data_length())
85 LOG(INFO) << " data_length: " << op.data_length();
86 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
87 if (op.has_src_length())
88 LOG(INFO) << " src_length: " << op.src_length();
89 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
90 if (op.has_dst_length())
91 LOG(INFO) << " dst_length: " << op.dst_length();
92 }
93}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070094
95// Opens path for read/write, put the fd into *fd. On success returns true
96// and sets *err to 0. On failure, returns false and sets *err to errno.
97bool OpenFile(const char* path, int* fd, int* err) {
98 if (*fd != -1) {
99 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
100 *err = EINVAL;
101 return false;
102 }
103 *fd = open(path, O_RDWR, 000);
104 if (*fd < 0) {
105 *err = errno;
106 PLOG(ERROR) << "Unable to open file " << path;
107 return false;
108 }
109 *err = 0;
110 return true;
111}
112
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700113} // namespace {}
114
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700115// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
116// it safely. Returns false otherwise.
117bool DeltaPerformer::IsIdempotentOperation(
118 const DeltaArchiveManifest_InstallOperation& op) {
119 if (op.src_extents_size() == 0) {
120 return true;
121 }
122 // TODO(adlr): detect other types of idempotent operations. For example,
123 // a MOVE may move a block onto itself.
124
125 // When in doubt, it's safe to declare an op non-idempotent.
126 ExtentRanges src_ranges;
127 src_ranges.AddRepeatedExtents(op.src_extents());
128 const uint64_t block_count = src_ranges.blocks();
129 src_ranges.SubtractRepeatedExtents(op.dst_extents());
130 return block_count == src_ranges.blocks();
131}
132
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700133int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700134 int err;
135 if (OpenFile(path, &fd_, &err))
136 path_ = path;
137 return -err;
138}
139
140bool DeltaPerformer::OpenKernel(const char* kernel_path) {
141 int err;
142 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
143 if (success)
144 kernel_path_ = kernel_path;
145 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700146}
147
148int DeltaPerformer::Close() {
149 if (!buffer_.empty()) {
150 LOG(ERROR) << "Called Close() while buffer not empty!";
151 return -1;
152 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700153 int err = 0;
154 if (close(kernel_fd_) == -1) {
155 err = errno;
156 PLOG(ERROR) << "Unable to close kernel fd:";
157 }
158 if (close(fd_) == -1) {
159 err = errno;
160 PLOG(ERROR) << "Unable to close rootfs fd:";
161 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700162 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700163 fd_ = -2; // Set so that isn't not valid AND calls to Open() will fail.
164 path_ = "";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700165 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700166}
167
168// Wrapper around write. Returns bytes written on success or
169// -errno on error.
170// This function performs as many actions as it can, given the amount of
171// data received thus far.
Andrew de los Reyes0cca4212010-04-29 14:00:58 -0700172ssize_t DeltaPerformer::Write(const void* bytes, size_t count) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700173 const char* c_bytes = reinterpret_cast<const char*>(bytes);
174 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
175
176 if (!manifest_valid_) {
177 // See if we have enough bytes for the manifest yet
178 if (buffer_.size() < strlen(kDeltaMagic) +
179 kDeltaVersionLength + kDeltaProtobufLengthLength) {
180 // Don't have enough bytes to even know the protobuf length
181 return count;
182 }
183 uint64_t protobuf_length;
184 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
185 protobuf_length_size_mismatch);
186 memcpy(&protobuf_length,
187 &buffer_[strlen(kDeltaMagic) + kDeltaVersionLength],
188 kDeltaProtobufLengthLength);
189 protobuf_length = be64toh(protobuf_length); // switch big endian to host
190 if (buffer_.size() < strlen(kDeltaMagic) + kDeltaVersionLength +
191 kDeltaProtobufLengthLength + protobuf_length) {
192 return count;
193 }
194 // We have the full proto buffer in buffer_. Parse it.
195 const int offset = strlen(kDeltaMagic) + kDeltaVersionLength +
196 kDeltaProtobufLengthLength;
197 if (!manifest_.ParseFromArray(&buffer_[offset], protobuf_length)) {
198 LOG(ERROR) << "Unable to parse manifest in update file.";
199 return -EINVAL;
200 }
201 // Remove protobuf and header info from buffer_, so buffer_ contains
202 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700203 manifest_metadata_size_ = strlen(kDeltaMagic) + kDeltaVersionLength +
Darin Petkov73058b42010-10-06 16:32:19 -0700204 kDeltaProtobufLengthLength + protobuf_length;
Darin Petkov437adc42010-10-07 13:12:24 -0700205 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700206 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700207 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700208 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700209 manifest_valid_ = true;
Darin Petkov9b230572010-10-08 10:20:09 -0700210 if (!PrimeUpdateState()) {
211 LOG(ERROR) << "Unable to prime the update state.";
212 return -EINVAL;
213 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700214 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700215 ssize_t total_operations = manifest_.install_operations_size() +
216 manifest_.kernel_install_operations_size();
217 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700218 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700219 next_operation_num_ < manifest_.install_operations_size() ?
220 manifest_.install_operations(next_operation_num_) :
221 manifest_.kernel_install_operations(
222 next_operation_num_ - manifest_.install_operations_size());
223 if (!CanPerformInstallOperation(op))
224 break;
Darin Petkov9c0baf82010-10-07 13:44:48 -0700225 ScopedTerminatorExitUnblocker exit_unblocker =
226 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700227 // Log every thousandth operation, and also the first and last ones
228 if ((next_operation_num_ % 1000 == 0) ||
229 (next_operation_num_ + 1 == total_operations)) {
230 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
231 << total_operations;
232 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700233 bool is_kernel_partition =
234 (next_operation_num_ >= manifest_.install_operations_size());
Darin Petkov73058b42010-10-06 16:32:19 -0700235 // If about to start a non-idempotent operation, clear the update state so
236 // that if the operation gets interrupted, we don't try to resume the
237 // update.
238 if (!IsIdempotentOperation(op)) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700239 Terminator::set_exit_blocked(true);
Darin Petkov9b230572010-10-08 10:20:09 -0700240 ResetUpdateProgress(prefs_, true);
Darin Petkov73058b42010-10-06 16:32:19 -0700241 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700242 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
243 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700244 if (!PerformReplaceOperation(op, is_kernel_partition)) {
245 LOG(ERROR) << "Failed to perform replace operation "
246 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700247 return -EINVAL;
248 }
249 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700250 if (!PerformMoveOperation(op, is_kernel_partition)) {
251 LOG(ERROR) << "Failed to perform move operation "
252 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700253 return -EINVAL;
254 }
255 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700256 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
257 LOG(ERROR) << "Failed to perform bsdiff operation "
258 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700259 return -EINVAL;
260 }
261 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700262 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700263 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700264 }
265 return count;
266}
267
268bool DeltaPerformer::CanPerformInstallOperation(
269 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
270 operation) {
271 // Move operations don't require any data blob, so they can always
272 // be performed
273 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
274 return true;
275
276 // See if we have the entire data blob in the buffer
277 if (operation.data_offset() < buffer_offset_) {
278 LOG(ERROR) << "we threw away data it seems?";
279 return false;
280 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700281
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700282 return (operation.data_offset() + operation.data_length()) <=
283 (buffer_offset_ + buffer_.size());
284}
285
286bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700287 const DeltaArchiveManifest_InstallOperation& operation,
288 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700289 CHECK(operation.type() == \
290 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
291 operation.type() == \
292 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
293
294 // Since we delete data off the beginning of the buffer as we use it,
295 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700296 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
297 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700298
Darin Petkov437adc42010-10-07 13:12:24 -0700299 // Extract the signature message if it's in this operation.
300 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700301
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700302 DirectExtentWriter direct_writer;
303 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
304 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700305
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700306 // Since bzip decompression is optional, we have a variable writer that will
307 // point to one of the ExtentWriter objects above.
308 ExtentWriter* writer = NULL;
309 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
310 writer = &zero_pad_writer;
311 } else if (operation.type() ==
312 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
313 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
314 writer = bzip_writer.get();
315 } else {
316 NOTREACHED();
317 }
318
319 // Create a vector of extents to pass to the ExtentWriter.
320 vector<Extent> extents;
321 for (int i = 0; i < operation.dst_extents_size(); i++) {
322 extents.push_back(operation.dst_extents(i));
323 }
324
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700325 int fd = is_kernel_partition ? kernel_fd_ : fd_;
326
327 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700328 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
329 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700330
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700331 // Update buffer
332 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700333 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700334 return true;
335}
336
337bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700338 const DeltaArchiveManifest_InstallOperation& operation,
339 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700340 // Calculate buffer size. Note, this function doesn't do a sliding
341 // window to copy in case the source and destination blocks overlap.
342 // If we wanted to do a sliding window, we could program the server
343 // to generate deltas that effectively did a sliding window.
344
345 uint64_t blocks_to_read = 0;
346 for (int i = 0; i < operation.src_extents_size(); i++)
347 blocks_to_read += operation.src_extents(i).num_blocks();
348
349 uint64_t blocks_to_write = 0;
350 for (int i = 0; i < operation.dst_extents_size(); i++)
351 blocks_to_write += operation.dst_extents(i).num_blocks();
352
353 DCHECK_EQ(blocks_to_write, blocks_to_read);
354 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700355
356 int fd = is_kernel_partition ? kernel_fd_ : fd_;
357
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700358 // Read in bytes.
359 ssize_t bytes_read = 0;
360 for (int i = 0; i < operation.src_extents_size(); i++) {
361 ssize_t bytes_read_this_iteration = 0;
362 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700363 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700364 &buf[bytes_read],
365 extent.num_blocks() * block_size_,
366 extent.start_block() * block_size_,
367 &bytes_read_this_iteration));
368 TEST_AND_RETURN_FALSE(
369 bytes_read_this_iteration ==
370 static_cast<ssize_t>(extent.num_blocks() * block_size_));
371 bytes_read += bytes_read_this_iteration;
372 }
373
374 // Write bytes out.
375 ssize_t bytes_written = 0;
376 for (int i = 0; i < operation.dst_extents_size(); i++) {
377 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700378 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700379 &buf[bytes_written],
380 extent.num_blocks() * block_size_,
381 extent.start_block() * block_size_));
382 bytes_written += extent.num_blocks() * block_size_;
383 }
384 DCHECK_EQ(bytes_written, bytes_read);
385 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
386 return true;
387}
388
389bool DeltaPerformer::ExtentsToBsdiffPositionsString(
390 const RepeatedPtrField<Extent>& extents,
391 uint64_t block_size,
392 uint64_t full_length,
393 string* positions_string) {
394 string ret;
395 uint64_t length = 0;
396 for (int i = 0; i < extents.size(); i++) {
397 Extent extent = extents.Get(i);
398 int64_t start = extent.start_block();
399 uint64_t this_length = min(full_length - length,
400 extent.num_blocks() * block_size);
401 if (start == static_cast<int64_t>(kSparseHole))
402 start = -1;
403 else
404 start *= block_size;
405 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
406 length += this_length;
407 }
408 TEST_AND_RETURN_FALSE(length == full_length);
409 if (!ret.empty())
410 ret.resize(ret.size() - 1); // Strip trailing comma off
411 *positions_string = ret;
412 return true;
413}
414
415bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700416 const DeltaArchiveManifest_InstallOperation& operation,
417 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700418 // Since we delete data off the beginning of the buffer as we use it,
419 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700420 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
421 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700422
423 string input_positions;
424 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
425 block_size_,
426 operation.src_length(),
427 &input_positions));
428 string output_positions;
429 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
430 block_size_,
431 operation.dst_length(),
432 &output_positions));
433
434 string temp_filename;
435 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
436 &temp_filename,
437 NULL));
438 ScopedPathUnlinker path_unlinker(temp_filename);
439 {
440 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
441 ScopedFdCloser fd_closer(&fd);
442 TEST_AND_RETURN_FALSE(
443 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
444 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700445
446 int fd = is_kernel_partition ? kernel_fd_ : fd_;
447 const string& path = is_kernel_partition ? kernel_path_ : path_;
448
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700449 vector<string> cmd;
450 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700451 cmd.push_back(path);
452 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700453 cmd.push_back(temp_filename);
454 cmd.push_back(input_positions);
455 cmd.push_back(output_positions);
456 int return_code = 0;
457 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &return_code));
458 TEST_AND_RETURN_FALSE(return_code == 0);
459
460 if (operation.dst_length() % block_size_) {
461 // Zero out rest of final block.
462 // TODO(adlr): build this into bspatch; it's more efficient that way.
463 const Extent& last_extent =
464 operation.dst_extents(operation.dst_extents_size() - 1);
465 const uint64_t end_byte =
466 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
467 const uint64_t begin_byte =
468 end_byte - (block_size_ - operation.dst_length() % block_size_);
469 vector<char> zeros(end_byte - begin_byte);
470 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700471 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700472 }
473
474 // Update buffer.
475 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700476 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700477 return true;
478}
479
Darin Petkovd7061ab2010-10-06 14:37:09 -0700480bool DeltaPerformer::ExtractSignatureMessage(
481 const DeltaArchiveManifest_InstallOperation& operation) {
482 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
483 !manifest_.has_signatures_offset() ||
484 manifest_.signatures_offset() != operation.data_offset()) {
485 return false;
486 }
487 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
488 manifest_.signatures_size() == operation.data_length());
489 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
490 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
491 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
492 signatures_message_data_.insert(
493 signatures_message_data_.begin(),
494 buffer_.begin(),
495 buffer_.begin() + manifest_.signatures_size());
Darin Petkov437adc42010-10-07 13:12:24 -0700496 // The hash of all data consumed so far should be verified against the signed
497 // hash.
498 signed_hash_context_ = hash_calculator_.GetContext();
499 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
500 signed_hash_context_))
501 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700502 LOG(INFO) << "Extracted signature data of size "
503 << manifest_.signatures_size() << " at "
504 << manifest_.signatures_offset();
505 return true;
506}
507
Darin Petkov437adc42010-10-07 13:12:24 -0700508bool DeltaPerformer::VerifyPayload(
509 const string& public_key_path,
510 const std::string& update_check_response_hash,
511 const uint64_t update_check_response_size) {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700512 string key_path = public_key_path;
513 if (key_path.empty()) {
514 key_path = kUpdatePayloadPublicKeyPath;
515 }
516 LOG(INFO) << "Verifying delta payload. Public key path: " << key_path;
Darin Petkov437adc42010-10-07 13:12:24 -0700517
518 // Verifies the download hash.
519 const string& download_hash_data = hash_calculator_.hash();
520 TEST_AND_RETURN_FALSE(!download_hash_data.empty());
521 TEST_AND_RETURN_FALSE(download_hash_data == update_check_response_hash);
522
523 // Verifies the download size.
524 TEST_AND_RETURN_FALSE(update_check_response_size ==
525 manifest_metadata_size_ + buffer_offset_);
526
527 // Verifies the signed payload hash.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700528 if (!utils::FileExists(key_path.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700529 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700530 return true;
531 }
532 TEST_AND_RETURN_FALSE(!signatures_message_data_.empty());
533 vector<char> signed_hash_data;
534 TEST_AND_RETURN_FALSE(PayloadSigner::VerifySignature(signatures_message_data_,
535 key_path,
536 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700537 OmahaHashCalculator signed_hasher;
538 // TODO(petkov): Make sure signed_hash_context_ is loaded when resuming an
539 // update.
540 TEST_AND_RETURN_FALSE(signed_hasher.SetContext(signed_hash_context_));
541 TEST_AND_RETURN_FALSE(signed_hasher.Finalize());
542 const vector<char>& hash_data = signed_hasher.raw_hash();
Darin Petkovd7061ab2010-10-06 14:37:09 -0700543 TEST_AND_RETURN_FALSE(!hash_data.empty());
Darin Petkov437adc42010-10-07 13:12:24 -0700544 TEST_AND_RETURN_FALSE(hash_data == signed_hash_data);
545 return true;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700546}
547
Darin Petkov437adc42010-10-07 13:12:24 -0700548void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
549 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700550 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
551}
552
Darin Petkov0406e402010-10-06 21:33:11 -0700553bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
554 string update_check_response_hash) {
555 int64_t next_operation = kUpdateStateOperationInvalid;
556 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
557 &next_operation) &&
558 next_operation != kUpdateStateOperationInvalid &&
559 next_operation > 0);
560
561 string interrupted_hash;
562 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
563 &interrupted_hash) &&
564 !interrupted_hash.empty() &&
565 interrupted_hash == update_check_response_hash);
566
Darin Petkov61426142010-10-08 11:04:55 -0700567 int64_t resumed_update_failures;
568 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
569 &resumed_update_failures) ||
570 resumed_update_failures <= kMaxResumedUpdateFailures);
571
Darin Petkov0406e402010-10-06 21:33:11 -0700572 // Sanity check the rest.
573 int64_t next_data_offset = -1;
574 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
575 &next_data_offset) &&
576 next_data_offset >= 0);
577
Darin Petkov437adc42010-10-07 13:12:24 -0700578 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700579 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700580 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
581 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700582
583 int64_t manifest_metadata_size = 0;
584 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
585 &manifest_metadata_size) &&
586 manifest_metadata_size > 0);
587
588 return true;
589}
590
Darin Petkov9b230572010-10-08 10:20:09 -0700591bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -0700592 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
593 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -0700594 if (!quick) {
595 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
596 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
597 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
598 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
599 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -0700600 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -0700601 }
Darin Petkov73058b42010-10-06 16:32:19 -0700602 return true;
603}
604
605bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700606 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -0700607 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700608 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -0700609 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -0700610 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700611 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -0700612 hash_calculator_.GetContext()));
613 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
614 buffer_offset_));
615 last_updated_buffer_offset_ = buffer_offset_;
616 }
Darin Petkov73058b42010-10-06 16:32:19 -0700617 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
618 next_operation_num_));
619 return true;
620}
621
Darin Petkov9b230572010-10-08 10:20:09 -0700622bool DeltaPerformer::PrimeUpdateState() {
623 CHECK(manifest_valid_);
624 block_size_ = manifest_.block_size();
625
626 int64_t next_operation = kUpdateStateOperationInvalid;
627 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
628 next_operation == kUpdateStateOperationInvalid ||
629 next_operation <= 0) {
630 // Initiating a new update, no more state needs to be initialized.
631 return true;
632 }
633 next_operation_num_ = next_operation;
634
635 // Resuming an update -- load the rest of the update state.
636 int64_t next_data_offset = -1;
637 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
638 &next_data_offset) &&
639 next_data_offset >= 0);
640 buffer_offset_ = next_data_offset;
641
642 // The signed hash context may be empty if the interrupted update didn't reach
643 // the signature blob.
644 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
645 &signed_hash_context_);
646
647 string hash_context;
648 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
649 &hash_context) &&
650 hash_calculator_.SetContext(hash_context));
651
652 int64_t manifest_metadata_size = 0;
653 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
654 &manifest_metadata_size) &&
655 manifest_metadata_size > 0);
656 manifest_metadata_size_ = manifest_metadata_size;
657
Darin Petkov61426142010-10-08 11:04:55 -0700658 // Speculatively count the resume as a failure.
659 int64_t resumed_update_failures;
660 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
661 resumed_update_failures++;
662 } else {
663 resumed_update_failures = 1;
664 }
665 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -0700666 return true;
667}
668
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700669} // namespace chromeos_update_engine