blob: 0eccb09782b7d93db1acaa19743536eff80f0030 [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"
21#include "update_engine/extent_writer.h"
22#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070023#include "update_engine/payload_signer.h"
Darin Petkov73058b42010-10-06 16:32:19 -070024#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070025#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070026#include "update_engine/terminator.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070027
28using std::min;
29using std::string;
30using std::vector;
31using google::protobuf::RepeatedPtrField;
32
33namespace chromeos_update_engine {
34
35namespace {
36
37const int kDeltaVersionLength = 8;
38const int kDeltaProtobufLengthLength = 8;
Darin Petkovd7061ab2010-10-06 14:37:09 -070039const char kUpdatePayloadPublicKeyPath[] =
40 "/usr/share/update_engine/update-payload-key.pub.pem";
Darin Petkov73058b42010-10-06 16:32:19 -070041const int kUpdateStateOperationInvalid = -1;
42
43// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
44// it safely. Returns false otherwise.
45bool IsIdempotentOperation(const DeltaArchiveManifest_InstallOperation& op) {
46 if (op.src_extents_size() == 0) {
47 return true;
48 }
49 // TODO(petkov): Cover the case where the source and target extents don't
50 // intersect.
51 return false;
52}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070053
54// Converts extents to a human-readable string, for use by DumpUpdateProto().
55string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
56 string ret;
57 for (int i = 0; i < extents.size(); i++) {
58 const Extent& extent = extents.Get(i);
59 if (extent.start_block() == kSparseHole) {
60 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
61 } else {
62 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
63 extent.start_block(), extent.num_blocks());
64 }
65 }
66 if (!ret.empty()) {
67 DCHECK_GT(ret.size(), static_cast<size_t>(1));
68 ret.resize(ret.size() - 2);
69 }
70 return ret;
71}
72
73// LOGs a DeltaArchiveManifest object. Useful for debugging.
74void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
75 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070076 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070077 for (int i = 0; i < (manifest.install_operations_size() +
78 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070079 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070080 i < manifest.install_operations_size() ?
81 manifest.install_operations(i) :
82 manifest.kernel_install_operations(
83 i - manifest.install_operations_size());
84 if (i == 0)
85 LOG(INFO) << " Rootfs ops:";
86 else if (i == manifest.install_operations_size())
87 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070088 LOG(INFO) << " operation(" << i << ")";
89 LOG(INFO) << " type: "
90 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
91 if (op.has_data_offset())
92 LOG(INFO) << " data_offset: " << op.data_offset();
93 if (op.has_data_length())
94 LOG(INFO) << " data_length: " << op.data_length();
95 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
96 if (op.has_src_length())
97 LOG(INFO) << " src_length: " << op.src_length();
98 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
99 if (op.has_dst_length())
100 LOG(INFO) << " dst_length: " << op.dst_length();
101 }
102}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700103
104// Opens path for read/write, put the fd into *fd. On success returns true
105// and sets *err to 0. On failure, returns false and sets *err to errno.
106bool OpenFile(const char* path, int* fd, int* err) {
107 if (*fd != -1) {
108 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
109 *err = EINVAL;
110 return false;
111 }
112 *fd = open(path, O_RDWR, 000);
113 if (*fd < 0) {
114 *err = errno;
115 PLOG(ERROR) << "Unable to open file " << path;
116 return false;
117 }
118 *err = 0;
119 return true;
120}
121
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700122} // namespace {}
123
124int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700125 int err;
126 if (OpenFile(path, &fd_, &err))
127 path_ = path;
128 return -err;
129}
130
131bool DeltaPerformer::OpenKernel(const char* kernel_path) {
132 int err;
133 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
134 if (success)
135 kernel_path_ = kernel_path;
136 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700137}
138
139int DeltaPerformer::Close() {
140 if (!buffer_.empty()) {
141 LOG(ERROR) << "Called Close() while buffer not empty!";
142 return -1;
143 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700144 int err = 0;
145 if (close(kernel_fd_) == -1) {
146 err = errno;
147 PLOG(ERROR) << "Unable to close kernel fd:";
148 }
149 if (close(fd_) == -1) {
150 err = errno;
151 PLOG(ERROR) << "Unable to close rootfs fd:";
152 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700153 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700154 fd_ = -2; // Set so that isn't not valid AND calls to Open() will fail.
155 path_ = "";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700156 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700157}
158
159// Wrapper around write. Returns bytes written on success or
160// -errno on error.
161// This function performs as many actions as it can, given the amount of
162// data received thus far.
Andrew de los Reyes0cca4212010-04-29 14:00:58 -0700163ssize_t DeltaPerformer::Write(const void* bytes, size_t count) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700164 const char* c_bytes = reinterpret_cast<const char*>(bytes);
165 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
166
167 if (!manifest_valid_) {
168 // See if we have enough bytes for the manifest yet
169 if (buffer_.size() < strlen(kDeltaMagic) +
170 kDeltaVersionLength + kDeltaProtobufLengthLength) {
171 // Don't have enough bytes to even know the protobuf length
172 return count;
173 }
174 uint64_t protobuf_length;
175 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
176 protobuf_length_size_mismatch);
177 memcpy(&protobuf_length,
178 &buffer_[strlen(kDeltaMagic) + kDeltaVersionLength],
179 kDeltaProtobufLengthLength);
180 protobuf_length = be64toh(protobuf_length); // switch big endian to host
181 if (buffer_.size() < strlen(kDeltaMagic) + kDeltaVersionLength +
182 kDeltaProtobufLengthLength + protobuf_length) {
183 return count;
184 }
185 // We have the full proto buffer in buffer_. Parse it.
186 const int offset = strlen(kDeltaMagic) + kDeltaVersionLength +
187 kDeltaProtobufLengthLength;
188 if (!manifest_.ParseFromArray(&buffer_[offset], protobuf_length)) {
189 LOG(ERROR) << "Unable to parse manifest in update file.";
190 return -EINVAL;
191 }
192 // Remove protobuf and header info from buffer_, so buffer_ contains
193 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700194 manifest_metadata_size_ = strlen(kDeltaMagic) + kDeltaVersionLength +
Darin Petkov73058b42010-10-06 16:32:19 -0700195 kDeltaProtobufLengthLength + protobuf_length;
Darin Petkov437adc42010-10-07 13:12:24 -0700196 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700197 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700198 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700199 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700200 manifest_valid_ = true;
Darin Petkov9b230572010-10-08 10:20:09 -0700201 if (!PrimeUpdateState()) {
202 LOG(ERROR) << "Unable to prime the update state.";
203 return -EINVAL;
204 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700205 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700206 ssize_t total_operations = manifest_.install_operations_size() +
207 manifest_.kernel_install_operations_size();
208 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700209 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700210 next_operation_num_ < manifest_.install_operations_size() ?
211 manifest_.install_operations(next_operation_num_) :
212 manifest_.kernel_install_operations(
213 next_operation_num_ - manifest_.install_operations_size());
214 if (!CanPerformInstallOperation(op))
215 break;
Darin Petkov9c0baf82010-10-07 13:44:48 -0700216 ScopedTerminatorExitUnblocker exit_unblocker =
217 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700218 // Log every thousandth operation, and also the first and last ones
219 if ((next_operation_num_ % 1000 == 0) ||
220 (next_operation_num_ + 1 == total_operations)) {
221 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
222 << total_operations;
223 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700224 bool is_kernel_partition =
225 (next_operation_num_ >= manifest_.install_operations_size());
Darin Petkov73058b42010-10-06 16:32:19 -0700226 // If about to start a non-idempotent operation, clear the update state so
227 // that if the operation gets interrupted, we don't try to resume the
228 // update.
229 if (!IsIdempotentOperation(op)) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700230 Terminator::set_exit_blocked(true);
Darin Petkov9b230572010-10-08 10:20:09 -0700231 ResetUpdateProgress(prefs_, true);
Darin Petkov73058b42010-10-06 16:32:19 -0700232 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700233 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
234 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700235 if (!PerformReplaceOperation(op, is_kernel_partition)) {
236 LOG(ERROR) << "Failed to perform replace operation "
237 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700238 return -EINVAL;
239 }
240 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700241 if (!PerformMoveOperation(op, is_kernel_partition)) {
242 LOG(ERROR) << "Failed to perform move operation "
243 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700244 return -EINVAL;
245 }
246 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700247 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
248 LOG(ERROR) << "Failed to perform bsdiff operation "
249 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700250 return -EINVAL;
251 }
252 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700253 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700254 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700255 }
256 return count;
257}
258
259bool DeltaPerformer::CanPerformInstallOperation(
260 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
261 operation) {
262 // Move operations don't require any data blob, so they can always
263 // be performed
264 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
265 return true;
266
267 // See if we have the entire data blob in the buffer
268 if (operation.data_offset() < buffer_offset_) {
269 LOG(ERROR) << "we threw away data it seems?";
270 return false;
271 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700272
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700273 return (operation.data_offset() + operation.data_length()) <=
274 (buffer_offset_ + buffer_.size());
275}
276
277bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700278 const DeltaArchiveManifest_InstallOperation& operation,
279 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700280 CHECK(operation.type() == \
281 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
282 operation.type() == \
283 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
284
285 // Since we delete data off the beginning of the buffer as we use it,
286 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700287 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
288 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700289
Darin Petkov437adc42010-10-07 13:12:24 -0700290 // Extract the signature message if it's in this operation.
291 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700292
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700293 DirectExtentWriter direct_writer;
294 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
295 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700296
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700297 // Since bzip decompression is optional, we have a variable writer that will
298 // point to one of the ExtentWriter objects above.
299 ExtentWriter* writer = NULL;
300 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
301 writer = &zero_pad_writer;
302 } else if (operation.type() ==
303 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
304 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
305 writer = bzip_writer.get();
306 } else {
307 NOTREACHED();
308 }
309
310 // Create a vector of extents to pass to the ExtentWriter.
311 vector<Extent> extents;
312 for (int i = 0; i < operation.dst_extents_size(); i++) {
313 extents.push_back(operation.dst_extents(i));
314 }
315
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700316 int fd = is_kernel_partition ? kernel_fd_ : fd_;
317
318 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700319 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
320 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700321
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700322 // Update buffer
323 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700324 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700325 return true;
326}
327
328bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700329 const DeltaArchiveManifest_InstallOperation& operation,
330 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700331 // Calculate buffer size. Note, this function doesn't do a sliding
332 // window to copy in case the source and destination blocks overlap.
333 // If we wanted to do a sliding window, we could program the server
334 // to generate deltas that effectively did a sliding window.
335
336 uint64_t blocks_to_read = 0;
337 for (int i = 0; i < operation.src_extents_size(); i++)
338 blocks_to_read += operation.src_extents(i).num_blocks();
339
340 uint64_t blocks_to_write = 0;
341 for (int i = 0; i < operation.dst_extents_size(); i++)
342 blocks_to_write += operation.dst_extents(i).num_blocks();
343
344 DCHECK_EQ(blocks_to_write, blocks_to_read);
345 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700346
347 int fd = is_kernel_partition ? kernel_fd_ : fd_;
348
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700349 // Read in bytes.
350 ssize_t bytes_read = 0;
351 for (int i = 0; i < operation.src_extents_size(); i++) {
352 ssize_t bytes_read_this_iteration = 0;
353 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700354 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700355 &buf[bytes_read],
356 extent.num_blocks() * block_size_,
357 extent.start_block() * block_size_,
358 &bytes_read_this_iteration));
359 TEST_AND_RETURN_FALSE(
360 bytes_read_this_iteration ==
361 static_cast<ssize_t>(extent.num_blocks() * block_size_));
362 bytes_read += bytes_read_this_iteration;
363 }
364
365 // Write bytes out.
366 ssize_t bytes_written = 0;
367 for (int i = 0; i < operation.dst_extents_size(); i++) {
368 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700369 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700370 &buf[bytes_written],
371 extent.num_blocks() * block_size_,
372 extent.start_block() * block_size_));
373 bytes_written += extent.num_blocks() * block_size_;
374 }
375 DCHECK_EQ(bytes_written, bytes_read);
376 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
377 return true;
378}
379
380bool DeltaPerformer::ExtentsToBsdiffPositionsString(
381 const RepeatedPtrField<Extent>& extents,
382 uint64_t block_size,
383 uint64_t full_length,
384 string* positions_string) {
385 string ret;
386 uint64_t length = 0;
387 for (int i = 0; i < extents.size(); i++) {
388 Extent extent = extents.Get(i);
389 int64_t start = extent.start_block();
390 uint64_t this_length = min(full_length - length,
391 extent.num_blocks() * block_size);
392 if (start == static_cast<int64_t>(kSparseHole))
393 start = -1;
394 else
395 start *= block_size;
396 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
397 length += this_length;
398 }
399 TEST_AND_RETURN_FALSE(length == full_length);
400 if (!ret.empty())
401 ret.resize(ret.size() - 1); // Strip trailing comma off
402 *positions_string = ret;
403 return true;
404}
405
406bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700407 const DeltaArchiveManifest_InstallOperation& operation,
408 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700409 // Since we delete data off the beginning of the buffer as we use it,
410 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700411 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
412 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700413
414 string input_positions;
415 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
416 block_size_,
417 operation.src_length(),
418 &input_positions));
419 string output_positions;
420 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
421 block_size_,
422 operation.dst_length(),
423 &output_positions));
424
425 string temp_filename;
426 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
427 &temp_filename,
428 NULL));
429 ScopedPathUnlinker path_unlinker(temp_filename);
430 {
431 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
432 ScopedFdCloser fd_closer(&fd);
433 TEST_AND_RETURN_FALSE(
434 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
435 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700436
437 int fd = is_kernel_partition ? kernel_fd_ : fd_;
438 const string& path = is_kernel_partition ? kernel_path_ : path_;
439
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700440 vector<string> cmd;
441 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700442 cmd.push_back(path);
443 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700444 cmd.push_back(temp_filename);
445 cmd.push_back(input_positions);
446 cmd.push_back(output_positions);
447 int return_code = 0;
448 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &return_code));
449 TEST_AND_RETURN_FALSE(return_code == 0);
450
451 if (operation.dst_length() % block_size_) {
452 // Zero out rest of final block.
453 // TODO(adlr): build this into bspatch; it's more efficient that way.
454 const Extent& last_extent =
455 operation.dst_extents(operation.dst_extents_size() - 1);
456 const uint64_t end_byte =
457 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
458 const uint64_t begin_byte =
459 end_byte - (block_size_ - operation.dst_length() % block_size_);
460 vector<char> zeros(end_byte - begin_byte);
461 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700462 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700463 }
464
465 // Update buffer.
466 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700467 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700468 return true;
469}
470
Darin Petkovd7061ab2010-10-06 14:37:09 -0700471bool DeltaPerformer::ExtractSignatureMessage(
472 const DeltaArchiveManifest_InstallOperation& operation) {
473 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
474 !manifest_.has_signatures_offset() ||
475 manifest_.signatures_offset() != operation.data_offset()) {
476 return false;
477 }
478 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
479 manifest_.signatures_size() == operation.data_length());
480 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
481 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
482 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
483 signatures_message_data_.insert(
484 signatures_message_data_.begin(),
485 buffer_.begin(),
486 buffer_.begin() + manifest_.signatures_size());
Darin Petkov437adc42010-10-07 13:12:24 -0700487 // The hash of all data consumed so far should be verified against the signed
488 // hash.
489 signed_hash_context_ = hash_calculator_.GetContext();
490 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
491 signed_hash_context_))
492 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700493 LOG(INFO) << "Extracted signature data of size "
494 << manifest_.signatures_size() << " at "
495 << manifest_.signatures_offset();
496 return true;
497}
498
Darin Petkov437adc42010-10-07 13:12:24 -0700499bool DeltaPerformer::VerifyPayload(
500 const string& public_key_path,
501 const std::string& update_check_response_hash,
502 const uint64_t update_check_response_size) {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700503 string key_path = public_key_path;
504 if (key_path.empty()) {
505 key_path = kUpdatePayloadPublicKeyPath;
506 }
507 LOG(INFO) << "Verifying delta payload. Public key path: " << key_path;
Darin Petkov437adc42010-10-07 13:12:24 -0700508
509 // Verifies the download hash.
510 const string& download_hash_data = hash_calculator_.hash();
511 TEST_AND_RETURN_FALSE(!download_hash_data.empty());
512 TEST_AND_RETURN_FALSE(download_hash_data == update_check_response_hash);
513
514 // Verifies the download size.
515 TEST_AND_RETURN_FALSE(update_check_response_size ==
516 manifest_metadata_size_ + buffer_offset_);
517
518 // Verifies the signed payload hash.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700519 if (!utils::FileExists(key_path.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700520 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700521 return true;
522 }
523 TEST_AND_RETURN_FALSE(!signatures_message_data_.empty());
524 vector<char> signed_hash_data;
525 TEST_AND_RETURN_FALSE(PayloadSigner::VerifySignature(signatures_message_data_,
526 key_path,
527 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700528 OmahaHashCalculator signed_hasher;
529 // TODO(petkov): Make sure signed_hash_context_ is loaded when resuming an
530 // update.
531 TEST_AND_RETURN_FALSE(signed_hasher.SetContext(signed_hash_context_));
532 TEST_AND_RETURN_FALSE(signed_hasher.Finalize());
533 const vector<char>& hash_data = signed_hasher.raw_hash();
Darin Petkovd7061ab2010-10-06 14:37:09 -0700534 TEST_AND_RETURN_FALSE(!hash_data.empty());
Darin Petkov437adc42010-10-07 13:12:24 -0700535 TEST_AND_RETURN_FALSE(hash_data == signed_hash_data);
536 return true;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700537}
538
Darin Petkov437adc42010-10-07 13:12:24 -0700539void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
540 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700541 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
542}
543
Darin Petkov0406e402010-10-06 21:33:11 -0700544bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
545 string update_check_response_hash) {
546 int64_t next_operation = kUpdateStateOperationInvalid;
547 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
548 &next_operation) &&
549 next_operation != kUpdateStateOperationInvalid &&
550 next_operation > 0);
551
552 string interrupted_hash;
553 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
554 &interrupted_hash) &&
555 !interrupted_hash.empty() &&
556 interrupted_hash == update_check_response_hash);
557
558 // Sanity check the rest.
559 int64_t next_data_offset = -1;
560 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
561 &next_data_offset) &&
562 next_data_offset >= 0);
563
Darin Petkov437adc42010-10-07 13:12:24 -0700564 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700565 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700566 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
567 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700568
569 int64_t manifest_metadata_size = 0;
570 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
571 &manifest_metadata_size) &&
572 manifest_metadata_size > 0);
573
574 return true;
575}
576
Darin Petkov9b230572010-10-08 10:20:09 -0700577bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -0700578 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
579 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -0700580 if (!quick) {
581 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
582 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
583 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
584 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
585 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
586 }
Darin Petkov73058b42010-10-06 16:32:19 -0700587 return true;
588}
589
590bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700591 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -0700592 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -0700593 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -0700594 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -0700595 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700596 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -0700597 hash_calculator_.GetContext()));
598 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
599 buffer_offset_));
600 last_updated_buffer_offset_ = buffer_offset_;
601 }
Darin Petkov73058b42010-10-06 16:32:19 -0700602 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
603 next_operation_num_));
604 return true;
605}
606
Darin Petkov9b230572010-10-08 10:20:09 -0700607bool DeltaPerformer::PrimeUpdateState() {
608 CHECK(manifest_valid_);
609 block_size_ = manifest_.block_size();
610
611 int64_t next_operation = kUpdateStateOperationInvalid;
612 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
613 next_operation == kUpdateStateOperationInvalid ||
614 next_operation <= 0) {
615 // Initiating a new update, no more state needs to be initialized.
616 return true;
617 }
618 next_operation_num_ = next_operation;
619
620 // Resuming an update -- load the rest of the update state.
621 int64_t next_data_offset = -1;
622 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
623 &next_data_offset) &&
624 next_data_offset >= 0);
625 buffer_offset_ = next_data_offset;
626
627 // The signed hash context may be empty if the interrupted update didn't reach
628 // the signature blob.
629 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
630 &signed_hash_context_);
631
632 string hash_context;
633 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
634 &hash_context) &&
635 hash_calculator_.SetContext(hash_context));
636
637 int64_t manifest_metadata_size = 0;
638 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
639 &manifest_metadata_size) &&
640 manifest_metadata_size > 0);
641 manifest_metadata_size_ = manifest_metadata_size;
642
643 return true;
644}
645
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700646} // namespace chromeos_update_engine