blob: f807665cbacffe092759d0f0977d4ae37f206f86 [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"
26
27using std::min;
28using std::string;
29using std::vector;
30using google::protobuf::RepeatedPtrField;
31
32namespace chromeos_update_engine {
33
34namespace {
35
36const int kDeltaVersionLength = 8;
37const int kDeltaProtobufLengthLength = 8;
Darin Petkovd7061ab2010-10-06 14:37:09 -070038const char kUpdatePayloadPublicKeyPath[] =
39 "/usr/share/update_engine/update-payload-key.pub.pem";
Darin Petkov73058b42010-10-06 16:32:19 -070040const int kUpdateStateOperationInvalid = -1;
41
42// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
43// it safely. Returns false otherwise.
44bool IsIdempotentOperation(const DeltaArchiveManifest_InstallOperation& op) {
45 if (op.src_extents_size() == 0) {
46 return true;
47 }
48 // TODO(petkov): Cover the case where the source and target extents don't
49 // intersect.
50 return false;
51}
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070052
53// Converts extents to a human-readable string, for use by DumpUpdateProto().
54string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
55 string ret;
56 for (int i = 0; i < extents.size(); i++) {
57 const Extent& extent = extents.Get(i);
58 if (extent.start_block() == kSparseHole) {
59 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
60 } else {
61 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
62 extent.start_block(), extent.num_blocks());
63 }
64 }
65 if (!ret.empty()) {
66 DCHECK_GT(ret.size(), static_cast<size_t>(1));
67 ret.resize(ret.size() - 2);
68 }
69 return ret;
70}
71
72// LOGs a DeltaArchiveManifest object. Useful for debugging.
73void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
74 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070075 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070076 for (int i = 0; i < (manifest.install_operations_size() +
77 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070078 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070079 i < manifest.install_operations_size() ?
80 manifest.install_operations(i) :
81 manifest.kernel_install_operations(
82 i - manifest.install_operations_size());
83 if (i == 0)
84 LOG(INFO) << " Rootfs ops:";
85 else if (i == manifest.install_operations_size())
86 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070087 LOG(INFO) << " operation(" << i << ")";
88 LOG(INFO) << " type: "
89 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
90 if (op.has_data_offset())
91 LOG(INFO) << " data_offset: " << op.data_offset();
92 if (op.has_data_length())
93 LOG(INFO) << " data_length: " << op.data_length();
94 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
95 if (op.has_src_length())
96 LOG(INFO) << " src_length: " << op.src_length();
97 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
98 if (op.has_dst_length())
99 LOG(INFO) << " dst_length: " << op.dst_length();
100 }
101}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700102
103// Opens path for read/write, put the fd into *fd. On success returns true
104// and sets *err to 0. On failure, returns false and sets *err to errno.
105bool OpenFile(const char* path, int* fd, int* err) {
106 if (*fd != -1) {
107 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
108 *err = EINVAL;
109 return false;
110 }
111 *fd = open(path, O_RDWR, 000);
112 if (*fd < 0) {
113 *err = errno;
114 PLOG(ERROR) << "Unable to open file " << path;
115 return false;
116 }
117 *err = 0;
118 return true;
119}
120
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700121} // namespace {}
122
123int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700124 int err;
125 if (OpenFile(path, &fd_, &err))
126 path_ = path;
127 return -err;
128}
129
130bool DeltaPerformer::OpenKernel(const char* kernel_path) {
131 int err;
132 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
133 if (success)
134 kernel_path_ = kernel_path;
135 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700136}
137
138int DeltaPerformer::Close() {
139 if (!buffer_.empty()) {
140 LOG(ERROR) << "Called Close() while buffer not empty!";
141 return -1;
142 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700143 int err = 0;
144 if (close(kernel_fd_) == -1) {
145 err = errno;
146 PLOG(ERROR) << "Unable to close kernel fd:";
147 }
148 if (close(fd_) == -1) {
149 err = errno;
150 PLOG(ERROR) << "Unable to close rootfs fd:";
151 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700152 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700153 fd_ = -2; // Set so that isn't not valid AND calls to Open() will fail.
154 path_ = "";
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700155 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700156}
157
158// Wrapper around write. Returns bytes written on success or
159// -errno on error.
160// This function performs as many actions as it can, given the amount of
161// data received thus far.
Andrew de los Reyes0cca4212010-04-29 14:00:58 -0700162ssize_t DeltaPerformer::Write(const void* bytes, size_t count) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700163 const char* c_bytes = reinterpret_cast<const char*>(bytes);
164 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
165
166 if (!manifest_valid_) {
167 // See if we have enough bytes for the manifest yet
168 if (buffer_.size() < strlen(kDeltaMagic) +
169 kDeltaVersionLength + kDeltaProtobufLengthLength) {
170 // Don't have enough bytes to even know the protobuf length
171 return count;
172 }
173 uint64_t protobuf_length;
174 COMPILE_ASSERT(sizeof(protobuf_length) == kDeltaProtobufLengthLength,
175 protobuf_length_size_mismatch);
176 memcpy(&protobuf_length,
177 &buffer_[strlen(kDeltaMagic) + kDeltaVersionLength],
178 kDeltaProtobufLengthLength);
179 protobuf_length = be64toh(protobuf_length); // switch big endian to host
180 if (buffer_.size() < strlen(kDeltaMagic) + kDeltaVersionLength +
181 kDeltaProtobufLengthLength + protobuf_length) {
182 return count;
183 }
184 // We have the full proto buffer in buffer_. Parse it.
185 const int offset = strlen(kDeltaMagic) + kDeltaVersionLength +
186 kDeltaProtobufLengthLength;
187 if (!manifest_.ParseFromArray(&buffer_[offset], protobuf_length)) {
188 LOG(ERROR) << "Unable to parse manifest in update file.";
189 return -EINVAL;
190 }
191 // Remove protobuf and header info from buffer_, so buffer_ contains
192 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700193 manifest_metadata_size_ = strlen(kDeltaMagic) + kDeltaVersionLength +
Darin Petkov73058b42010-10-06 16:32:19 -0700194 kDeltaProtobufLengthLength + protobuf_length;
Darin Petkov437adc42010-10-07 13:12:24 -0700195 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700196 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700197 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700198 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700199 manifest_valid_ = true;
200 block_size_ = manifest_.block_size();
201 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700202 ssize_t total_operations = manifest_.install_operations_size() +
203 manifest_.kernel_install_operations_size();
204 while (next_operation_num_ < total_operations) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700205 const DeltaArchiveManifest_InstallOperation &op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700206 next_operation_num_ < manifest_.install_operations_size() ?
207 manifest_.install_operations(next_operation_num_) :
208 manifest_.kernel_install_operations(
209 next_operation_num_ - manifest_.install_operations_size());
210 if (!CanPerformInstallOperation(op))
211 break;
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700212 // Log every thousandth operation, and also the first and last ones
213 if ((next_operation_num_ % 1000 == 0) ||
214 (next_operation_num_ + 1 == total_operations)) {
215 LOG(INFO) << "Performing operation " << (next_operation_num_ + 1) << "/"
216 << total_operations;
217 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700218 bool is_kernel_partition =
219 (next_operation_num_ >= manifest_.install_operations_size());
Darin Petkov73058b42010-10-06 16:32:19 -0700220 // If about to start a non-idempotent operation, clear the update state so
221 // that if the operation gets interrupted, we don't try to resume the
222 // update.
223 if (!IsIdempotentOperation(op)) {
Darin Petkov0406e402010-10-06 21:33:11 -0700224 ResetUpdateProgress(prefs_);
Darin Petkov73058b42010-10-06 16:32:19 -0700225 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700226 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
227 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700228 if (!PerformReplaceOperation(op, is_kernel_partition)) {
229 LOG(ERROR) << "Failed to perform replace operation "
230 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700231 return -EINVAL;
232 }
233 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700234 if (!PerformMoveOperation(op, is_kernel_partition)) {
235 LOG(ERROR) << "Failed to perform move operation "
236 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700237 return -EINVAL;
238 }
239 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700240 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
241 LOG(ERROR) << "Failed to perform bsdiff operation "
242 << next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700243 return -EINVAL;
244 }
245 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700246 next_operation_num_++;
Darin Petkov73058b42010-10-06 16:32:19 -0700247 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700248 }
249 return count;
250}
251
252bool DeltaPerformer::CanPerformInstallOperation(
253 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
254 operation) {
255 // Move operations don't require any data blob, so they can always
256 // be performed
257 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
258 return true;
259
260 // See if we have the entire data blob in the buffer
261 if (operation.data_offset() < buffer_offset_) {
262 LOG(ERROR) << "we threw away data it seems?";
263 return false;
264 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700265
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700266 return (operation.data_offset() + operation.data_length()) <=
267 (buffer_offset_ + buffer_.size());
268}
269
270bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700271 const DeltaArchiveManifest_InstallOperation& operation,
272 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700273 CHECK(operation.type() == \
274 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
275 operation.type() == \
276 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
277
278 // Since we delete data off the beginning of the buffer as we use it,
279 // the data we need should be exactly at the beginning of the buffer.
280 CHECK_EQ(buffer_offset_, operation.data_offset());
281 CHECK_GE(buffer_.size(), operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700282
Darin Petkov437adc42010-10-07 13:12:24 -0700283 // Extract the signature message if it's in this operation.
284 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700285
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700286 DirectExtentWriter direct_writer;
287 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
288 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700289
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700290 // Since bzip decompression is optional, we have a variable writer that will
291 // point to one of the ExtentWriter objects above.
292 ExtentWriter* writer = NULL;
293 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
294 writer = &zero_pad_writer;
295 } else if (operation.type() ==
296 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
297 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
298 writer = bzip_writer.get();
299 } else {
300 NOTREACHED();
301 }
302
303 // Create a vector of extents to pass to the ExtentWriter.
304 vector<Extent> extents;
305 for (int i = 0; i < operation.dst_extents_size(); i++) {
306 extents.push_back(operation.dst_extents(i));
307 }
308
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700309 int fd = is_kernel_partition ? kernel_fd_ : fd_;
310
311 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700312 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
313 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700314
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700315 // Update buffer
316 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700317 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700318 return true;
319}
320
321bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700322 const DeltaArchiveManifest_InstallOperation& operation,
323 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700324 // Calculate buffer size. Note, this function doesn't do a sliding
325 // window to copy in case the source and destination blocks overlap.
326 // If we wanted to do a sliding window, we could program the server
327 // to generate deltas that effectively did a sliding window.
328
329 uint64_t blocks_to_read = 0;
330 for (int i = 0; i < operation.src_extents_size(); i++)
331 blocks_to_read += operation.src_extents(i).num_blocks();
332
333 uint64_t blocks_to_write = 0;
334 for (int i = 0; i < operation.dst_extents_size(); i++)
335 blocks_to_write += operation.dst_extents(i).num_blocks();
336
337 DCHECK_EQ(blocks_to_write, blocks_to_read);
338 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700339
340 int fd = is_kernel_partition ? kernel_fd_ : fd_;
341
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700342 // Read in bytes.
343 ssize_t bytes_read = 0;
344 for (int i = 0; i < operation.src_extents_size(); i++) {
345 ssize_t bytes_read_this_iteration = 0;
346 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700347 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700348 &buf[bytes_read],
349 extent.num_blocks() * block_size_,
350 extent.start_block() * block_size_,
351 &bytes_read_this_iteration));
352 TEST_AND_RETURN_FALSE(
353 bytes_read_this_iteration ==
354 static_cast<ssize_t>(extent.num_blocks() * block_size_));
355 bytes_read += bytes_read_this_iteration;
356 }
357
358 // Write bytes out.
359 ssize_t bytes_written = 0;
360 for (int i = 0; i < operation.dst_extents_size(); i++) {
361 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700362 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700363 &buf[bytes_written],
364 extent.num_blocks() * block_size_,
365 extent.start_block() * block_size_));
366 bytes_written += extent.num_blocks() * block_size_;
367 }
368 DCHECK_EQ(bytes_written, bytes_read);
369 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
370 return true;
371}
372
373bool DeltaPerformer::ExtentsToBsdiffPositionsString(
374 const RepeatedPtrField<Extent>& extents,
375 uint64_t block_size,
376 uint64_t full_length,
377 string* positions_string) {
378 string ret;
379 uint64_t length = 0;
380 for (int i = 0; i < extents.size(); i++) {
381 Extent extent = extents.Get(i);
382 int64_t start = extent.start_block();
383 uint64_t this_length = min(full_length - length,
384 extent.num_blocks() * block_size);
385 if (start == static_cast<int64_t>(kSparseHole))
386 start = -1;
387 else
388 start *= block_size;
389 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
390 length += this_length;
391 }
392 TEST_AND_RETURN_FALSE(length == full_length);
393 if (!ret.empty())
394 ret.resize(ret.size() - 1); // Strip trailing comma off
395 *positions_string = ret;
396 return true;
397}
398
399bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700400 const DeltaArchiveManifest_InstallOperation& operation,
401 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700402 // Since we delete data off the beginning of the buffer as we use it,
403 // the data we need should be exactly at the beginning of the buffer.
404 CHECK_EQ(buffer_offset_, operation.data_offset());
405 CHECK_GE(buffer_.size(), operation.data_length());
406
407 string input_positions;
408 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
409 block_size_,
410 operation.src_length(),
411 &input_positions));
412 string output_positions;
413 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
414 block_size_,
415 operation.dst_length(),
416 &output_positions));
417
418 string temp_filename;
419 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
420 &temp_filename,
421 NULL));
422 ScopedPathUnlinker path_unlinker(temp_filename);
423 {
424 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
425 ScopedFdCloser fd_closer(&fd);
426 TEST_AND_RETURN_FALSE(
427 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
428 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700429
430 int fd = is_kernel_partition ? kernel_fd_ : fd_;
431 const string& path = is_kernel_partition ? kernel_path_ : path_;
432
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700433 vector<string> cmd;
434 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700435 cmd.push_back(path);
436 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700437 cmd.push_back(temp_filename);
438 cmd.push_back(input_positions);
439 cmd.push_back(output_positions);
440 int return_code = 0;
441 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &return_code));
442 TEST_AND_RETURN_FALSE(return_code == 0);
443
444 if (operation.dst_length() % block_size_) {
445 // Zero out rest of final block.
446 // TODO(adlr): build this into bspatch; it's more efficient that way.
447 const Extent& last_extent =
448 operation.dst_extents(operation.dst_extents_size() - 1);
449 const uint64_t end_byte =
450 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
451 const uint64_t begin_byte =
452 end_byte - (block_size_ - operation.dst_length() % block_size_);
453 vector<char> zeros(end_byte - begin_byte);
454 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700455 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700456 }
457
458 // Update buffer.
459 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700460 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700461 return true;
462}
463
Darin Petkovd7061ab2010-10-06 14:37:09 -0700464bool DeltaPerformer::ExtractSignatureMessage(
465 const DeltaArchiveManifest_InstallOperation& operation) {
466 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
467 !manifest_.has_signatures_offset() ||
468 manifest_.signatures_offset() != operation.data_offset()) {
469 return false;
470 }
471 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
472 manifest_.signatures_size() == operation.data_length());
473 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
474 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
475 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
476 signatures_message_data_.insert(
477 signatures_message_data_.begin(),
478 buffer_.begin(),
479 buffer_.begin() + manifest_.signatures_size());
Darin Petkov437adc42010-10-07 13:12:24 -0700480 // The hash of all data consumed so far should be verified against the signed
481 // hash.
482 signed_hash_context_ = hash_calculator_.GetContext();
483 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
484 signed_hash_context_))
485 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700486 LOG(INFO) << "Extracted signature data of size "
487 << manifest_.signatures_size() << " at "
488 << manifest_.signatures_offset();
489 return true;
490}
491
Darin Petkov437adc42010-10-07 13:12:24 -0700492bool DeltaPerformer::VerifyPayload(
493 const string& public_key_path,
494 const std::string& update_check_response_hash,
495 const uint64_t update_check_response_size) {
Darin Petkovd7061ab2010-10-06 14:37:09 -0700496 string key_path = public_key_path;
497 if (key_path.empty()) {
498 key_path = kUpdatePayloadPublicKeyPath;
499 }
500 LOG(INFO) << "Verifying delta payload. Public key path: " << key_path;
Darin Petkov437adc42010-10-07 13:12:24 -0700501
502 // Verifies the download hash.
503 const string& download_hash_data = hash_calculator_.hash();
504 TEST_AND_RETURN_FALSE(!download_hash_data.empty());
505 TEST_AND_RETURN_FALSE(download_hash_data == update_check_response_hash);
506
507 // Verifies the download size.
508 TEST_AND_RETURN_FALSE(update_check_response_size ==
509 manifest_metadata_size_ + buffer_offset_);
510
511 // Verifies the signed payload hash.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700512 if (!utils::FileExists(key_path.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700513 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700514 return true;
515 }
516 TEST_AND_RETURN_FALSE(!signatures_message_data_.empty());
517 vector<char> signed_hash_data;
518 TEST_AND_RETURN_FALSE(PayloadSigner::VerifySignature(signatures_message_data_,
519 key_path,
520 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700521 OmahaHashCalculator signed_hasher;
522 // TODO(petkov): Make sure signed_hash_context_ is loaded when resuming an
523 // update.
524 TEST_AND_RETURN_FALSE(signed_hasher.SetContext(signed_hash_context_));
525 TEST_AND_RETURN_FALSE(signed_hasher.Finalize());
526 const vector<char>& hash_data = signed_hasher.raw_hash();
Darin Petkovd7061ab2010-10-06 14:37:09 -0700527 TEST_AND_RETURN_FALSE(!hash_data.empty());
Darin Petkov437adc42010-10-07 13:12:24 -0700528 TEST_AND_RETURN_FALSE(hash_data == signed_hash_data);
529 return true;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700530}
531
Darin Petkov437adc42010-10-07 13:12:24 -0700532void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
533 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700534 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
535}
536
Darin Petkov0406e402010-10-06 21:33:11 -0700537bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
538 string update_check_response_hash) {
539 int64_t next_operation = kUpdateStateOperationInvalid;
540 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
541 &next_operation) &&
542 next_operation != kUpdateStateOperationInvalid &&
543 next_operation > 0);
544
545 string interrupted_hash;
546 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
547 &interrupted_hash) &&
548 !interrupted_hash.empty() &&
549 interrupted_hash == update_check_response_hash);
550
551 // Sanity check the rest.
552 int64_t next_data_offset = -1;
553 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
554 &next_data_offset) &&
555 next_data_offset >= 0);
556
Darin Petkov437adc42010-10-07 13:12:24 -0700557 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -0700558 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700559 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
560 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -0700561
562 int64_t manifest_metadata_size = 0;
563 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
564 &manifest_metadata_size) &&
565 manifest_metadata_size > 0);
566
567 return true;
568}
569
570bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs) {
571 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
572 kUpdateStateOperationInvalid));
Darin Petkov73058b42010-10-06 16:32:19 -0700573 return true;
574}
575
576bool DeltaPerformer::CheckpointUpdateProgress() {
577 // First reset the progress in case we die in the middle of the state update.
Darin Petkov0406e402010-10-06 21:33:11 -0700578 ResetUpdateProgress(prefs_);
579 if (last_updated_buffer_offset_ != buffer_offset_) {
580 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -0700581 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -0700582 hash_calculator_.GetContext()));
583 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
584 buffer_offset_));
585 last_updated_buffer_offset_ = buffer_offset_;
586 }
Darin Petkov73058b42010-10-06 16:32:19 -0700587 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
588 next_operation_num_));
589 return true;
590}
591
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700592} // namespace chromeos_update_engine