blob: 9bf3d34ad49bc9fd62d1830ec09c24bf683bd167 [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;
43
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070044// Converts extents to a human-readable string, for use by DumpUpdateProto().
45string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
46 string ret;
47 for (int i = 0; i < extents.size(); i++) {
48 const Extent& extent = extents.Get(i);
49 if (extent.start_block() == kSparseHole) {
50 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
51 } else {
52 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
53 extent.start_block(), extent.num_blocks());
54 }
55 }
56 if (!ret.empty()) {
57 DCHECK_GT(ret.size(), static_cast<size_t>(1));
58 ret.resize(ret.size() - 2);
59 }
60 return ret;
61}
62
63// LOGs a DeltaArchiveManifest object. Useful for debugging.
64void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
65 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070066 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070067 for (int i = 0; i < (manifest.install_operations_size() +
68 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070069 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070070 i < manifest.install_operations_size() ?
71 manifest.install_operations(i) :
72 manifest.kernel_install_operations(
73 i - manifest.install_operations_size());
74 if (i == 0)
75 LOG(INFO) << " Rootfs ops:";
76 else if (i == manifest.install_operations_size())
77 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070078 LOG(INFO) << " operation(" << i << ")";
79 LOG(INFO) << " type: "
80 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
81 if (op.has_data_offset())
82 LOG(INFO) << " data_offset: " << op.data_offset();
83 if (op.has_data_length())
84 LOG(INFO) << " data_length: " << op.data_length();
85 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
86 if (op.has_src_length())
87 LOG(INFO) << " src_length: " << op.src_length();
88 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
89 if (op.has_dst_length())
90 LOG(INFO) << " dst_length: " << op.dst_length();
91 }
92}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070093
94// Opens path for read/write, put the fd into *fd. On success returns true
95// and sets *err to 0. On failure, returns false and sets *err to errno.
96bool OpenFile(const char* path, int* fd, int* err) {
97 if (*fd != -1) {
98 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
99 *err = EINVAL;
100 return false;
101 }
102 *fd = open(path, O_RDWR, 000);
103 if (*fd < 0) {
104 *err = errno;
105 PLOG(ERROR) << "Unable to open file " << path;
106 return false;
107 }
108 *err = 0;
109 return true;
110}
111
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700112} // namespace {}
113
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700114// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
115// it safely. Returns false otherwise.
116bool DeltaPerformer::IsIdempotentOperation(
117 const DeltaArchiveManifest_InstallOperation& op) {
118 if (op.src_extents_size() == 0) {
119 return true;
120 }
121 // TODO(adlr): detect other types of idempotent operations. For example,
122 // a MOVE may move a block onto itself.
123
124 // When in doubt, it's safe to declare an op non-idempotent.
125 ExtentRanges src_ranges;
126 src_ranges.AddRepeatedExtents(op.src_extents());
127 const uint64_t block_count = src_ranges.blocks();
128 src_ranges.SubtractRepeatedExtents(op.dst_extents());
129 return block_count == src_ranges.blocks();
130}
131
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700132int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700133 int err;
134 if (OpenFile(path, &fd_, &err))
135 path_ = path;
136 return -err;
137}
138
139bool DeltaPerformer::OpenKernel(const char* kernel_path) {
140 int err;
141 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
142 if (success)
143 kernel_path_ = kernel_path;
144 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700145}
146
147int DeltaPerformer::Close() {
148 if (!buffer_.empty()) {
149 LOG(ERROR) << "Called Close() while buffer not empty!";
150 return -1;
151 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700152 int err = 0;
153 if (close(kernel_fd_) == -1) {
154 err = errno;
155 PLOG(ERROR) << "Unable to close kernel fd:";
156 }
157 if (close(fd_) == -1) {
158 err = errno;
159 PLOG(ERROR) << "Unable to close rootfs fd:";
160 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700161 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162 fd_ = -2; // Set so that isn't not valid AND calls to Open() will fail.
163 path_ = "";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700164 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700165}
166
167// Wrapper around write. Returns bytes written on success or
168// -errno on error.
169// This function performs as many actions as it can, given the amount of
170// data received thus far.
Andrew de los Reyes0cca4212010-04-29 14:00:58 -0700171ssize_t DeltaPerformer::Write(const void* bytes, size_t count) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700172 const char* c_bytes = reinterpret_cast<const char*>(bytes);
173 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
174
175 if (!manifest_valid_) {
176 // See if we have enough bytes for the manifest yet
177 if (buffer_.size() < strlen(kDeltaMagic) +
178 kDeltaVersionLength + kDeltaProtobufLengthLength) {
179 // Don't have enough bytes to even know the protobuf length
180 return count;
181 }
182 uint64_t protobuf_length;
183 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
184 protobuf_length_size_mismatch);
185 memcpy(&protobuf_length,
186 &buffer_[strlen(kDeltaMagic) + kDeltaVersionLength],
187 kDeltaProtobufLengthLength);
188 protobuf_length = be64toh(protobuf_length); // switch big endian to host
189 if (buffer_.size() < strlen(kDeltaMagic) + kDeltaVersionLength +
190 kDeltaProtobufLengthLength + protobuf_length) {
191 return count;
192 }
193 // We have the full proto buffer in buffer_. Parse it.
194 const int offset = strlen(kDeltaMagic) + kDeltaVersionLength +
195 kDeltaProtobufLengthLength;
196 if (!manifest_.ParseFromArray(&buffer_[offset], protobuf_length)) {
197 LOG(ERROR) << "Unable to parse manifest in update file.";
198 return -EINVAL;
199 }
200 // Remove protobuf and header info from buffer_, so buffer_ contains
201 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700202 manifest_metadata_size_ = strlen(kDeltaMagic) + kDeltaVersionLength +
Darin Petkov73058b42010-10-06 16:32:19 -0700203 kDeltaProtobufLengthLength + protobuf_length;
Darin Petkov437adc42010-10-07 13:12:24 -0700204 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700205 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700206 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700207 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700208 manifest_valid_ = true;
Darin Petkov9b230572010-10-08 10:20:09 -0700209 if (!PrimeUpdateState()) {
210 LOG(ERROR) << "Unable to prime the update state.";
211 return -EINVAL;
212 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700213 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700214 ssize_t total_operations = manifest_.install_operations_size() +
215 manifest_.kernel_install_operations_size();
216 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700217 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700218 next_operation_num_ < manifest_.install_operations_size() ?
219 manifest_.install_operations(next_operation_num_) :
220 manifest_.kernel_install_operations(
221 next_operation_num_ - manifest_.install_operations_size());
222 if (!CanPerformInstallOperation(op))
223 break;
Darin Petkov9c0baf82010-10-07 13:44:48 -0700224 ScopedTerminatorExitUnblocker exit_unblocker =
225 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700226 // Log every thousandth operation, and also the first and last ones
227 if ((next_operation_num_ % 1000 == 0) ||
228 (next_operation_num_ + 1 == total_operations)) {
229 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
230 << total_operations;
231 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700232 bool is_kernel_partition =
233 (next_operation_num_ >= manifest_.install_operations_size());
Darin Petkov73058b42010-10-06 16:32:19 -0700234 // If about to start a non-idempotent operation, clear the update state so
235 // that if the operation gets interrupted, we don't try to resume the
236 // update.
237 if (!IsIdempotentOperation(op)) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700238 Terminator::set_exit_blocked(true);
Darin Petkov9b230572010-10-08 10:20:09 -0700239 ResetUpdateProgress(prefs_, true);
Darin Petkov73058b42010-10-06 16:32:19 -0700240 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700241 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
242 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700243 if (!PerformReplaceOperation(op, is_kernel_partition)) {
244 LOG(ERROR) << "Failed to perform replace operation "
245 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700246 return -EINVAL;
247 }
248 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700249 if (!PerformMoveOperation(op, is_kernel_partition)) {
250 LOG(ERROR) << "Failed to perform move operation "
251 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700252 return -EINVAL;
253 }
254 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700255 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
256 LOG(ERROR) << "Failed to perform bsdiff operation "
257 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700258 return -EINVAL;
259 }
260 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700261 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700262 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700263 }
264 return count;
265}
266
267bool DeltaPerformer::CanPerformInstallOperation(
268 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
269 operation) {
270 // Move operations don't require any data blob, so they can always
271 // be performed
272 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
273 return true;
274
275 // See if we have the entire data blob in the buffer
276 if (operation.data_offset() < buffer_offset_) {
277 LOG(ERROR) << "we threw away data it seems?";
278 return false;
279 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700280
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700281 return (operation.data_offset() + operation.data_length()) <=
282 (buffer_offset_ + buffer_.size());
283}
284
285bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700286 const DeltaArchiveManifest_InstallOperation& operation,
287 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700288 CHECK(operation.type() == \
289 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
290 operation.type() == \
291 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
292
293 // Since we delete data off the beginning of the buffer as we use it,
294 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700295 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
296 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700297
Darin Petkov437adc42010-10-07 13:12:24 -0700298 // Extract the signature message if it's in this operation.
299 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700300
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700301 DirectExtentWriter direct_writer;
302 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
303 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700304
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700305 // Since bzip decompression is optional, we have a variable writer that will
306 // point to one of the ExtentWriter objects above.
307 ExtentWriter* writer = NULL;
308 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
309 writer = &zero_pad_writer;
310 } else if (operation.type() ==
311 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
312 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
313 writer = bzip_writer.get();
314 } else {
315 NOTREACHED();
316 }
317
318 // Create a vector of extents to pass to the ExtentWriter.
319 vector<Extent> extents;
320 for (int i = 0; i < operation.dst_extents_size(); i++) {
321 extents.push_back(operation.dst_extents(i));
322 }
323
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700324 int fd = is_kernel_partition ? kernel_fd_ : fd_;
325
326 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700327 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
328 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700329
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700330 // Update buffer
331 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700332 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700333 return true;
334}
335
336bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700337 const DeltaArchiveManifest_InstallOperation& operation,
338 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700339 // Calculate buffer size. Note, this function doesn't do a sliding
340 // window to copy in case the source and destination blocks overlap.
341 // If we wanted to do a sliding window, we could program the server
342 // to generate deltas that effectively did a sliding window.
343
344 uint64_t blocks_to_read = 0;
345 for (int i = 0; i < operation.src_extents_size(); i++)
346 blocks_to_read += operation.src_extents(i).num_blocks();
347
348 uint64_t blocks_to_write = 0;
349 for (int i = 0; i < operation.dst_extents_size(); i++)
350 blocks_to_write += operation.dst_extents(i).num_blocks();
351
352 DCHECK_EQ(blocks_to_write, blocks_to_read);
353 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700354
355 int fd = is_kernel_partition ? kernel_fd_ : fd_;
356
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700357 // Read in bytes.
358 ssize_t bytes_read = 0;
359 for (int i = 0; i < operation.src_extents_size(); i++) {
360 ssize_t bytes_read_this_iteration = 0;
361 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700362 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700363 &buf[bytes_read],
364 extent.num_blocks() * block_size_,
365 extent.start_block() * block_size_,
366 &bytes_read_this_iteration));
367 TEST_AND_RETURN_FALSE(
368 bytes_read_this_iteration ==
369 static_cast<ssize_t>(extent.num_blocks() * block_size_));
370 bytes_read += bytes_read_this_iteration;
371 }
372
373 // Write bytes out.
374 ssize_t bytes_written = 0;
375 for (int i = 0; i < operation.dst_extents_size(); i++) {
376 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700377 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700378 &buf[bytes_written],
379 extent.num_blocks() * block_size_,
380 extent.start_block() * block_size_));
381 bytes_written += extent.num_blocks() * block_size_;
382 }
383 DCHECK_EQ(bytes_written, bytes_read);
384 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
385 return true;
386}
387
388bool DeltaPerformer::ExtentsToBsdiffPositionsString(
389 const RepeatedPtrField<Extent>& extents,
390 uint64_t block_size,
391 uint64_t full_length,
392 string* positions_string) {
393 string ret;
394 uint64_t length = 0;
395 for (int i = 0; i < extents.size(); i++) {
396 Extent extent = extents.Get(i);
397 int64_t start = extent.start_block();
398 uint64_t this_length = min(full_length - length,
399 extent.num_blocks() * block_size);
400 if (start == static_cast<int64_t>(kSparseHole))
401 start = -1;
402 else
403 start *= block_size;
404 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
405 length += this_length;
406 }
407 TEST_AND_RETURN_FALSE(length == full_length);
408 if (!ret.empty())
409 ret.resize(ret.size() - 1); // Strip trailing comma off
410 *positions_string = ret;
411 return true;
412}
413
414bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700415 const DeltaArchiveManifest_InstallOperation& operation,
416 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700417 // Since we delete data off the beginning of the buffer as we use it,
418 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700419 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
420 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700421
422 string input_positions;
423 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
424 block_size_,
425 operation.src_length(),
426 &input_positions));
427 string output_positions;
428 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
429 block_size_,
430 operation.dst_length(),
431 &output_positions));
432
433 string temp_filename;
434 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
435 &temp_filename,
436 NULL));
437 ScopedPathUnlinker path_unlinker(temp_filename);
438 {
439 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
440 ScopedFdCloser fd_closer(&fd);
441 TEST_AND_RETURN_FALSE(
442 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
443 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700444
445 int fd = is_kernel_partition ? kernel_fd_ : fd_;
446 const string& path = is_kernel_partition ? kernel_path_ : path_;
447
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700448 vector<string> cmd;
449 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700450 cmd.push_back(path);
451 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700452 cmd.push_back(temp_filename);
453 cmd.push_back(input_positions);
454 cmd.push_back(output_positions);
455 int return_code = 0;
456 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &return_code));
457 TEST_AND_RETURN_FALSE(return_code == 0);
458
459 if (operation.dst_length() % block_size_) {
460 // Zero out rest of final block.
461 // TODO(adlr): build this into bspatch; it's more efficient that way.
462 const Extent& last_extent =
463 operation.dst_extents(operation.dst_extents_size() - 1);
464 const uint64_t end_byte =
465 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
466 const uint64_t begin_byte =
467 end_byte - (block_size_ - operation.dst_length() % block_size_);
468 vector<char> zeros(end_byte - begin_byte);
469 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700470 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700471 }
472
473 // Update buffer.
474 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700475 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700476 return true;
477}
478
Darin Petkovd7061ab2010-10-06 14:37:09 -0700479bool DeltaPerformer::ExtractSignatureMessage(
480 const DeltaArchiveManifest_InstallOperation& operation) {
481 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
482 !manifest_.has_signatures_offset() ||
483 manifest_.signatures_offset() != operation.data_offset()) {
484 return false;
485 }
486 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
487 manifest_.signatures_size() == operation.data_length());
488 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
489 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
490 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
491 signatures_message_data_.insert(
492 signatures_message_data_.begin(),
493 buffer_.begin(),
494 buffer_.begin() + manifest_.signatures_size());
Darin Petkov437adc42010-10-07 13:12:24 -0700495 // The hash of all data consumed so far should be verified against the signed
496 // hash.
497 signed_hash_context_ = hash_calculator_.GetContext();
498 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
499 signed_hash_context_))
500 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700501 LOG(INFO) << "Extracted signature data of size "
502 << manifest_.signatures_size() << " at "
503 << manifest_.signatures_offset();
504 return true;
505}
506
Darin Petkov437adc42010-10-07 13:12:24 -0700507bool DeltaPerformer::VerifyPayload(
508 const string& public_key_path,
509 const std::string& update_check_response_hash,
510 const uint64_t update_check_response_size) {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700511 string key_path = public_key_path;
512 if (key_path.empty()) {
513 key_path = kUpdatePayloadPublicKeyPath;
514 }
515 LOG(INFO) << "Verifying delta payload. Public key path: " << key_path;
Darin Petkov437adc42010-10-07 13:12:24 -0700516
517 // Verifies the download hash.
518 const string& download_hash_data = hash_calculator_.hash();
519 TEST_AND_RETURN_FALSE(!download_hash_data.empty());
520 TEST_AND_RETURN_FALSE(download_hash_data == update_check_response_hash);
521
522 // Verifies the download size.
523 TEST_AND_RETURN_FALSE(update_check_response_size ==
524 manifest_metadata_size_ + buffer_offset_);
525
526 // Verifies the signed payload hash.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700527 if (!utils::FileExists(key_path.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700528 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700529 return true;
530 }
531 TEST_AND_RETURN_FALSE(!signatures_message_data_.empty());
532 vector<char> signed_hash_data;
533 TEST_AND_RETURN_FALSE(PayloadSigner::VerifySignature(signatures_message_data_,
534 key_path,
535 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700536 OmahaHashCalculator signed_hasher;
537 // TODO(petkov): Make sure signed_hash_context_ is loaded when resuming an
538 // update.
539 TEST_AND_RETURN_FALSE(signed_hasher.SetContext(signed_hash_context_));
540 TEST_AND_RETURN_FALSE(signed_hasher.Finalize());
541 const vector<char>& hash_data = signed_hasher.raw_hash();
Darin Petkovd7061ab2010-10-06 14:37:09 -0700542 TEST_AND_RETURN_FALSE(!hash_data.empty());
Darin Petkov437adc42010-10-07 13:12:24 -0700543 TEST_AND_RETURN_FALSE(hash_data == signed_hash_data);
544 return true;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700545}
546
Darin Petkov437adc42010-10-07 13:12:24 -0700547void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
548 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700549 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
550}
551
Darin Petkov0406e402010-10-06 21:33:11 -0700552bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
553 string update_check_response_hash) {
554 int64_t next_operation = kUpdateStateOperationInvalid;
555 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
556 &next_operation) &&
557 next_operation != kUpdateStateOperationInvalid &&
558 next_operation > 0);
559
560 string interrupted_hash;
561 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
562 &interrupted_hash) &&
563 !interrupted_hash.empty() &&
564 interrupted_hash == update_check_response_hash);
565
566 // Sanity check the rest.
567 int64_t next_data_offset = -1;
568 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
569 &next_data_offset) &&
570 next_data_offset >= 0);
571
Darin Petkov437adc42010-10-07 13:12:24 -0700572 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700573 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700574 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
575 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700576
577 int64_t manifest_metadata_size = 0;
578 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
579 &manifest_metadata_size) &&
580 manifest_metadata_size > 0);
581
582 return true;
583}
584
Darin Petkov9b230572010-10-08 10:20:09 -0700585bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -0700586 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
587 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -0700588 if (!quick) {
589 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
590 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
591 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
592 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
593 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
594 }
Darin Petkov73058b42010-10-06 16:32:19 -0700595 return true;
596}
597
598bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700599 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -0700600 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700601 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -0700602 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -0700603 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700604 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -0700605 hash_calculator_.GetContext()));
606 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
607 buffer_offset_));
608 last_updated_buffer_offset_ = buffer_offset_;
609 }
Darin Petkov73058b42010-10-06 16:32:19 -0700610 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
611 next_operation_num_));
612 return true;
613}
614
Darin Petkov9b230572010-10-08 10:20:09 -0700615bool DeltaPerformer::PrimeUpdateState() {
616 CHECK(manifest_valid_);
617 block_size_ = manifest_.block_size();
618
619 int64_t next_operation = kUpdateStateOperationInvalid;
620 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
621 next_operation == kUpdateStateOperationInvalid ||
622 next_operation <= 0) {
623 // Initiating a new update, no more state needs to be initialized.
624 return true;
625 }
626 next_operation_num_ = next_operation;
627
628 // Resuming an update -- load the rest of the update state.
629 int64_t next_data_offset = -1;
630 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
631 &next_data_offset) &&
632 next_data_offset >= 0);
633 buffer_offset_ = next_data_offset;
634
635 // The signed hash context may be empty if the interrupted update didn't reach
636 // the signature blob.
637 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
638 &signed_hash_context_);
639
640 string hash_context;
641 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
642 &hash_context) &&
643 hash_calculator_.SetContext(hash_context));
644
645 int64_t manifest_metadata_size = 0;
646 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
647 &manifest_metadata_size) &&
648 manifest_metadata_size > 0);
649 manifest_metadata_size_ = manifest_metadata_size;
650
651 return true;
652}
653
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654} // namespace chromeos_update_engine