blob: c299d7929c6094ef3fd52c7bcceeb90f1015c9b7 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -07006
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07007#include <endian.h>
8#include <errno.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -07009
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070010#include <algorithm>
11#include <cstring>
12#include <string>
13#include <vector>
14
Chris Masoned903c3b2011-05-12 15:35:46 -070015#include <base/memory/scoped_ptr.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070016#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040017#include <base/stringprintf.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070018#include <google/protobuf/repeated_field.h>
19
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070020#include "update_engine/bzip_extent_writer.h"
21#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070022#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/extent_writer.h"
24#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070025#include "update_engine/payload_signer.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080026#include "update_engine/payload_state_interface.h"
Darin Petkov73058b42010-10-06 16:32:19 -070027#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070028#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070029#include "update_engine/terminator.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070030
31using std::min;
32using std::string;
33using std::vector;
34using google::protobuf::RepeatedPtrField;
35
36namespace chromeos_update_engine {
37
Jay Srinivasanf4318702012-09-24 11:56:24 -070038const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
39const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Darin Petkovabc7bc02011-02-23 14:39:43 -080040const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
41 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080042const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
43const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
44const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
45const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080046
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070047namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070048const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070049const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070050
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070051// Converts extents to a human-readable string, for use by DumpUpdateProto().
52string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
53 string ret;
54 for (int i = 0; i < extents.size(); i++) {
55 const Extent& extent = extents.Get(i);
56 if (extent.start_block() == kSparseHole) {
57 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
58 } else {
59 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
60 extent.start_block(), extent.num_blocks());
61 }
62 }
63 if (!ret.empty()) {
64 DCHECK_GT(ret.size(), static_cast<size_t>(1));
65 ret.resize(ret.size() - 2);
66 }
67 return ret;
68}
69
70// LOGs a DeltaArchiveManifest object. Useful for debugging.
71void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
72 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070073 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070074 for (int i = 0; i < (manifest.install_operations_size() +
75 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070076 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070077 i < manifest.install_operations_size() ?
78 manifest.install_operations(i) :
79 manifest.kernel_install_operations(
80 i - manifest.install_operations_size());
81 if (i == 0)
82 LOG(INFO) << " Rootfs ops:";
83 else if (i == manifest.install_operations_size())
84 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070085 LOG(INFO) << " operation(" << i << ")";
86 LOG(INFO) << " type: "
87 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
88 if (op.has_data_offset())
89 LOG(INFO) << " data_offset: " << op.data_offset();
90 if (op.has_data_length())
91 LOG(INFO) << " data_length: " << op.data_length();
92 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
93 if (op.has_src_length())
94 LOG(INFO) << " src_length: " << op.src_length();
95 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
96 if (op.has_dst_length())
97 LOG(INFO) << " dst_length: " << op.dst_length();
98 }
99}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700100
101// Opens path for read/write, put the fd into *fd. On success returns true
102// and sets *err to 0. On failure, returns false and sets *err to errno.
103bool OpenFile(const char* path, int* fd, int* err) {
104 if (*fd != -1) {
105 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
106 *err = EINVAL;
107 return false;
108 }
109 *fd = open(path, O_RDWR, 000);
110 if (*fd < 0) {
111 *err = errno;
112 PLOG(ERROR) << "Unable to open file " << path;
113 return false;
114 }
115 *err = 0;
116 return true;
117}
118
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700119} // namespace {}
120
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800121
122// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
123// arithmetic.
124static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
125 return part * norm / total;
126}
127
128void DeltaPerformer::LogProgress(const char* message_prefix) {
129 // Format operations total count and percentage.
130 string total_operations_str("?");
131 string completed_percentage_str("");
132 if (num_total_operations_) {
133 total_operations_str = StringPrintf("%zu", num_total_operations_);
134 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
135 completed_percentage_str =
136 StringPrintf(" (%llu%%)",
137 IntRatio(next_operation_num_, num_total_operations_,
138 100));
139 }
140
141 // Format download total count and percentage.
142 size_t payload_size = install_plan_->payload_size;
143 string payload_size_str("?");
144 string downloaded_percentage_str("");
145 if (payload_size) {
146 payload_size_str = StringPrintf("%zu", payload_size);
147 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
148 downloaded_percentage_str =
149 StringPrintf(" (%llu%%)",
150 IntRatio(total_bytes_received_, payload_size, 100));
151 }
152
153 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
154 << "/" << total_operations_str << " operations"
155 << completed_percentage_str << ", " << total_bytes_received_
156 << "/" << payload_size_str << " bytes downloaded"
157 << downloaded_percentage_str << ", overall progress "
158 << overall_progress_ << "%";
159}
160
161void DeltaPerformer::UpdateOverallProgress(bool force_log,
162 const char* message_prefix) {
163 // Compute our download and overall progress.
164 unsigned new_overall_progress = 0;
165 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
166 progress_weight_dont_add_up);
167 // Only consider download progress if its total size is known; otherwise
168 // adjust the operations weight to compensate for the absence of download
169 // progress. Also, make sure to cap the download portion at
170 // kProgressDownloadWeight, in case we end up downloading more than we
171 // initially expected (this indicates a problem, but could generally happen).
172 // TODO(garnold) the correction of operations weight when we do not have the
173 // total payload size, as well as the conditional guard below, should both be
174 // eliminated once we ensure that the payload_size in the install plan is
175 // always given and is non-zero. This currently isn't the case during unit
176 // tests (see chromium-os:37969).
177 size_t payload_size = install_plan_->payload_size;
178 unsigned actual_operations_weight = kProgressOperationsWeight;
179 if (payload_size)
180 new_overall_progress += min(
181 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
182 kProgressDownloadWeight)),
183 kProgressDownloadWeight);
184 else
185 actual_operations_weight += kProgressDownloadWeight;
186
187 // Only add completed operations if their total number is known; we definitely
188 // expect an update to have at least one operation, so the expectation is that
189 // this will eventually reach |actual_operations_weight|.
190 if (num_total_operations_)
191 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
192 actual_operations_weight);
193
194 // Progress ratio cannot recede, unless our assumptions about the total
195 // payload size, total number of operations, or the monotonicity of progress
196 // is breached.
197 if (new_overall_progress < overall_progress_) {
198 LOG(WARNING) << "progress counter receded from " << overall_progress_
199 << "% down to " << new_overall_progress << "%; this is a bug";
200 force_log = true;
201 }
202 overall_progress_ = new_overall_progress;
203
204 // Update chunk index, log as needed: if forced by called, or we completed a
205 // progress chunk, or a timeout has expired.
206 base::Time curr_time = base::Time::Now();
207 unsigned curr_progress_chunk =
208 overall_progress_ * kProgressLogMaxChunks / 100;
209 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
210 curr_time > forced_progress_log_time_) {
211 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
212 LogProgress(message_prefix);
213 }
214 last_progress_chunk_ = curr_progress_chunk;
215}
216
217
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700218// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
219// it safely. Returns false otherwise.
220bool DeltaPerformer::IsIdempotentOperation(
221 const DeltaArchiveManifest_InstallOperation& op) {
222 if (op.src_extents_size() == 0) {
223 return true;
224 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700225 // When in doubt, it's safe to declare an op non-idempotent. Note that we
226 // could detect other types of idempotent operations here such as a MOVE that
227 // moves blocks onto themselves. However, we rely on the server to not send
228 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700229 ExtentRanges src_ranges;
230 src_ranges.AddRepeatedExtents(op.src_extents());
231 const uint64_t block_count = src_ranges.blocks();
232 src_ranges.SubtractRepeatedExtents(op.dst_extents());
233 return block_count == src_ranges.blocks();
234}
235
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700236int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700237 int err;
238 if (OpenFile(path, &fd_, &err))
239 path_ = path;
240 return -err;
241}
242
243bool DeltaPerformer::OpenKernel(const char* kernel_path) {
244 int err;
245 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
246 if (success)
247 kernel_path_ = kernel_path;
248 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700249}
250
251int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700252 int err = 0;
253 if (close(kernel_fd_) == -1) {
254 err = errno;
255 PLOG(ERROR) << "Unable to close kernel fd:";
256 }
257 if (close(fd_) == -1) {
258 err = errno;
259 PLOG(ERROR) << "Unable to close rootfs fd:";
260 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700261 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800262 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700263 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800264 if (!buffer_.empty()) {
265 LOG(ERROR) << "Called Close() while buffer not empty!";
266 if (err >= 0) {
267 err = 1;
268 }
269 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700270 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700271}
272
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700273namespace {
274
275void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
276 string sha256;
277 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
278 info.hash().size(),
279 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800280 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
281 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700282 } else {
283 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
284 }
285}
286
287void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
288 if (manifest.has_old_kernel_info())
289 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
290 if (manifest.has_old_rootfs_info())
291 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
292 if (manifest.has_new_kernel_info())
293 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
294 if (manifest.has_new_rootfs_info())
295 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
296}
297
298} // namespace {}
299
Jay Srinivasanf4318702012-09-24 11:56:24 -0700300uint64_t DeltaPerformer::GetManifestSizeOffset() {
301 // Manifest size is stored right after the magic string and the version.
302 return strlen(kDeltaMagic) + kDeltaVersionSize;
303}
304
305uint64_t DeltaPerformer::GetManifestOffset() {
306 // Actual manifest begins right after the manifest size field.
307 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
308}
309
310
Darin Petkov9574f7e2011-01-13 10:48:12 -0800311DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
312 const std::vector<char>& payload,
313 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700314 uint64_t* metadata_size,
315 ActionExitCode* error) {
316 *error = kActionCodeSuccess;
317
Jay Srinivasanf4318702012-09-24 11:56:24 -0700318 // manifest_offset is the byte offset where the manifest protobuf begins.
319 const uint64_t manifest_offset = GetManifestOffset();
320 if (payload.size() < manifest_offset) {
321 // Don't have enough bytes to even know the manifest size.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800322 return kMetadataParseInsufficientData;
323 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700324
Jay Srinivasanf4318702012-09-24 11:56:24 -0700325 // Validate the magic string.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800326 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
327 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700328 *error = kActionCodeDownloadInvalidMetadataMagicString;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800329 return kMetadataParseError;
330 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700331
332 // TODO(jaysri): Compare the version number and skip unknown manifest
333 // versions. We don't check the version at all today.
334
Jay Srinivasanf4318702012-09-24 11:56:24 -0700335 // Next, parse the manifest size.
336 uint64_t manifest_size;
337 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
338 manifest_size_size_mismatch);
339 memcpy(&manifest_size,
340 &payload[GetManifestSizeOffset()],
341 kDeltaManifestSizeSize);
342 manifest_size = be64toh(manifest_size); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700343
344 // Now, check if the metasize we computed matches what was passed in
345 // through Omaha Response.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700346 *metadata_size = manifest_offset + manifest_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700347
Jay Srinivasanf4318702012-09-24 11:56:24 -0700348 // If the metadata size is present in install plan, check for it immediately
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700349 // even before waiting for that many number of bytes to be downloaded
350 // in the payload. This will prevent any attack which relies on us downloading
Jay Srinivasanf4318702012-09-24 11:56:24 -0700351 // data beyond the expected metadata size.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800352 if (install_plan_->hash_checks_mandatory) {
353 if (install_plan_->metadata_size != *metadata_size) {
354 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
355 << install_plan_->metadata_size << ") is missing/incorrect."
356 << ", Actual = " << *metadata_size;
357 *error = kActionCodeDownloadInvalidMetadataSize;
358 return kMetadataParseError;
359 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700360 }
361
362 // Now that we have validated the metadata size, we should wait for the full
363 // metadata to be read in before we can parse it.
364 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800365 return kMetadataParseInsufficientData;
366 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700367
368 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700369 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700370 // that we just log once (instead of logging n times) if it takes n
371 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800372 if (install_plan_->metadata_size == *metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700373 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800374 } else {
375 // For mandatory-cases, we'd have already returned a kMetadataParseError
376 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
377 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
378 << install_plan_->metadata_size
379 << ") in Omaha response as validation is not mandatory. "
380 << "Trusting metadata size in payload = " << *metadata_size;
381 SendUmaStat(kActionCodeDownloadInvalidMetadataSize);
382 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700383
Jay Srinivasanf4318702012-09-24 11:56:24 -0700384 // We have the full metadata in |payload|. Verify its integrity
385 // and authenticity based on the information we have in Omaha response.
386 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700387 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800388 if (install_plan_->hash_checks_mandatory) {
389 LOG(ERROR) << "Mandatory metadata signature validation failed";
390 return kMetadataParseError;
391 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700392
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800393 // For non-mandatory cases, just send a UMA stat.
394 LOG(WARNING) << "Ignoring metadata signature validation failures";
395 SendUmaStat(*error);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700396 *error = kActionCodeSuccess;
397 }
398
Jay Srinivasanf4318702012-09-24 11:56:24 -0700399 // The metadata in |payload| is deemed valid. So, it's now safe to
400 // parse the protobuf.
401 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800402 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700403 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800404 return kMetadataParseError;
405 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800406 return kMetadataParseSuccess;
407}
408
409
Don Garrette410e0f2011-11-10 15:39:01 -0800410// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800411// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700412// and stores an action exit code in |error|.
413bool DeltaPerformer::Write(const void* bytes, size_t count,
414 ActionExitCode *error) {
415 *error = kActionCodeSuccess;
416
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700417 const char* c_bytes = reinterpret_cast<const char*>(bytes);
418 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800419 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800420
421 // Update the total byte downloaded count and the progress logs.
422 total_bytes_received_ += count;
423 UpdateOverallProgress(false, "Completed ");
424
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700425 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800426 MetadataParseResult result = ParsePayloadMetadata(buffer_,
427 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700428 &manifest_metadata_size_,
429 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800430 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800431 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800432 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800433 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800434 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700435 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700436 // Remove protobuf and header info from buffer_, so buffer_ contains
437 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700438 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700439 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700440 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700441 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700442 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700443
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700444 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700445 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700446 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700447 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800448 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700449 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800450
451 num_rootfs_operations_ = manifest_.install_operations_size();
452 num_total_operations_ =
453 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
454 if (next_operation_num_ > 0)
455 UpdateOverallProgress(true, "Resuming after ");
456 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700457 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800458
459 while (next_operation_num_ < num_total_operations_) {
460 const bool is_kernel_partition =
461 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700462 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800463 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700464 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800465 next_operation_num_ - num_rootfs_operations_) :
466 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700467 if (!CanPerformInstallOperation(op)) {
468 // This means we don't have enough bytes received yet to carry out the
469 // next operation.
470 return true;
471 }
472
Jay Srinivasanf4318702012-09-24 11:56:24 -0700473 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700474 // Otherwise, keep the old behavior. This serves as a knob to disable
475 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800476 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
477 // we would have already failed in ParsePayloadMetadata method and thus not
478 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700479 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700480 // Note: Validate must be called only if CanPerformInstallOperation is
481 // called. Otherwise, we might be failing operations before even if there
482 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800483 *error = ValidateOperationHash(op);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700484 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800485 if (install_plan_->hash_checks_mandatory) {
486 LOG(ERROR) << "Mandatory operation hash check failed";
487 return false;
488 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700489
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800490 // For non-mandatory cases, just send a UMA stat.
491 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700492 SendUmaStat(*error);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800493 *error = kActionCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700494 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700495 }
496
Darin Petkov45580e42010-10-08 14:02:40 -0700497 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700498 ScopedTerminatorExitUnblocker exit_unblocker =
499 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700500 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700501 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
502 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700503 if (!PerformReplaceOperation(op, is_kernel_partition)) {
504 LOG(ERROR) << "Failed to perform replace operation "
505 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700506 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800507 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700508 }
509 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700510 if (!PerformMoveOperation(op, is_kernel_partition)) {
511 LOG(ERROR) << "Failed to perform move operation "
512 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700513 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800514 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700515 }
516 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700517 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
518 LOG(ERROR) << "Failed to perform bsdiff operation "
519 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700520 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800521 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700522 }
523 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800524
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700525 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800526 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700527 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700528 }
Don Garrette410e0f2011-11-10 15:39:01 -0800529 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700530}
531
532bool DeltaPerformer::CanPerformInstallOperation(
533 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
534 operation) {
535 // Move operations don't require any data blob, so they can always
536 // be performed
537 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
538 return true;
539
540 // See if we have the entire data blob in the buffer
541 if (operation.data_offset() < buffer_offset_) {
542 LOG(ERROR) << "we threw away data it seems?";
543 return false;
544 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700545
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700546 return (operation.data_offset() + operation.data_length()) <=
547 (buffer_offset_ + buffer_.size());
548}
549
550bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700551 const DeltaArchiveManifest_InstallOperation& operation,
552 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700553 CHECK(operation.type() == \
554 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
555 operation.type() == \
556 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
557
558 // Since we delete data off the beginning of the buffer as we use it,
559 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700560 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
561 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700562
Darin Petkov437adc42010-10-07 13:12:24 -0700563 // Extract the signature message if it's in this operation.
564 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700565
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700566 DirectExtentWriter direct_writer;
567 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
568 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700569
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700570 // Since bzip decompression is optional, we have a variable writer that will
571 // point to one of the ExtentWriter objects above.
572 ExtentWriter* writer = NULL;
573 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
574 writer = &zero_pad_writer;
575 } else if (operation.type() ==
576 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
577 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
578 writer = bzip_writer.get();
579 } else {
580 NOTREACHED();
581 }
582
583 // Create a vector of extents to pass to the ExtentWriter.
584 vector<Extent> extents;
585 for (int i = 0; i < operation.dst_extents_size(); i++) {
586 extents.push_back(operation.dst_extents(i));
587 }
588
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700589 int fd = is_kernel_partition ? kernel_fd_ : fd_;
590
591 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700592 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
593 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700594
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700595 // Update buffer
596 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700597 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700598 return true;
599}
600
601bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700602 const DeltaArchiveManifest_InstallOperation& operation,
603 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700604 // Calculate buffer size. Note, this function doesn't do a sliding
605 // window to copy in case the source and destination blocks overlap.
606 // If we wanted to do a sliding window, we could program the server
607 // to generate deltas that effectively did a sliding window.
608
609 uint64_t blocks_to_read = 0;
610 for (int i = 0; i < operation.src_extents_size(); i++)
611 blocks_to_read += operation.src_extents(i).num_blocks();
612
613 uint64_t blocks_to_write = 0;
614 for (int i = 0; i < operation.dst_extents_size(); i++)
615 blocks_to_write += operation.dst_extents(i).num_blocks();
616
617 DCHECK_EQ(blocks_to_write, blocks_to_read);
618 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700619
620 int fd = is_kernel_partition ? kernel_fd_ : fd_;
621
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700622 // Read in bytes.
623 ssize_t bytes_read = 0;
624 for (int i = 0; i < operation.src_extents_size(); i++) {
625 ssize_t bytes_read_this_iteration = 0;
626 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700627 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700628 &buf[bytes_read],
629 extent.num_blocks() * block_size_,
630 extent.start_block() * block_size_,
631 &bytes_read_this_iteration));
632 TEST_AND_RETURN_FALSE(
633 bytes_read_this_iteration ==
634 static_cast<ssize_t>(extent.num_blocks() * block_size_));
635 bytes_read += bytes_read_this_iteration;
636 }
637
Darin Petkov45580e42010-10-08 14:02:40 -0700638 // If this is a non-idempotent operation, request a delayed exit and clear the
639 // update state in case the operation gets interrupted. Do this as late as
640 // possible.
641 if (!IsIdempotentOperation(operation)) {
642 Terminator::set_exit_blocked(true);
643 ResetUpdateProgress(prefs_, true);
644 }
645
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700646 // Write bytes out.
647 ssize_t bytes_written = 0;
648 for (int i = 0; i < operation.dst_extents_size(); i++) {
649 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700650 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700651 &buf[bytes_written],
652 extent.num_blocks() * block_size_,
653 extent.start_block() * block_size_));
654 bytes_written += extent.num_blocks() * block_size_;
655 }
656 DCHECK_EQ(bytes_written, bytes_read);
657 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
658 return true;
659}
660
661bool DeltaPerformer::ExtentsToBsdiffPositionsString(
662 const RepeatedPtrField<Extent>& extents,
663 uint64_t block_size,
664 uint64_t full_length,
665 string* positions_string) {
666 string ret;
667 uint64_t length = 0;
668 for (int i = 0; i < extents.size(); i++) {
669 Extent extent = extents.Get(i);
670 int64_t start = extent.start_block();
671 uint64_t this_length = min(full_length - length,
672 extent.num_blocks() * block_size);
673 if (start == static_cast<int64_t>(kSparseHole))
674 start = -1;
675 else
676 start *= block_size;
677 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
678 length += this_length;
679 }
680 TEST_AND_RETURN_FALSE(length == full_length);
681 if (!ret.empty())
682 ret.resize(ret.size() - 1); // Strip trailing comma off
683 *positions_string = ret;
684 return true;
685}
686
687bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700688 const DeltaArchiveManifest_InstallOperation& operation,
689 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700690 // Since we delete data off the beginning of the buffer as we use it,
691 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700692 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
693 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700694
695 string input_positions;
696 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
697 block_size_,
698 operation.src_length(),
699 &input_positions));
700 string output_positions;
701 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
702 block_size_,
703 operation.dst_length(),
704 &output_positions));
705
706 string temp_filename;
707 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
708 &temp_filename,
709 NULL));
710 ScopedPathUnlinker path_unlinker(temp_filename);
711 {
712 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
713 ScopedFdCloser fd_closer(&fd);
714 TEST_AND_RETURN_FALSE(
715 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
716 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700717
718 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700719 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700720
Darin Petkov45580e42010-10-08 14:02:40 -0700721 // If this is a non-idempotent operation, request a delayed exit and clear the
722 // update state in case the operation gets interrupted. Do this as late as
723 // possible.
724 if (!IsIdempotentOperation(operation)) {
725 Terminator::set_exit_blocked(true);
726 ResetUpdateProgress(prefs_, true);
727 }
728
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700729 vector<string> cmd;
730 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700731 cmd.push_back(path);
732 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700733 cmd.push_back(temp_filename);
734 cmd.push_back(input_positions);
735 cmd.push_back(output_positions);
736 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700737 TEST_AND_RETURN_FALSE(
738 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700739 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700740 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700741 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700742 TEST_AND_RETURN_FALSE(return_code == 0);
743
744 if (operation.dst_length() % block_size_) {
745 // Zero out rest of final block.
746 // TODO(adlr): build this into bspatch; it's more efficient that way.
747 const Extent& last_extent =
748 operation.dst_extents(operation.dst_extents_size() - 1);
749 const uint64_t end_byte =
750 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
751 const uint64_t begin_byte =
752 end_byte - (block_size_ - operation.dst_length() % block_size_);
753 vector<char> zeros(end_byte - begin_byte);
754 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700755 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700756 }
757
758 // Update buffer.
759 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700760 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700761 return true;
762}
763
Darin Petkovd7061ab2010-10-06 14:37:09 -0700764bool DeltaPerformer::ExtractSignatureMessage(
765 const DeltaArchiveManifest_InstallOperation& operation) {
766 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
767 !manifest_.has_signatures_offset() ||
768 manifest_.signatures_offset() != operation.data_offset()) {
769 return false;
770 }
771 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
772 manifest_.signatures_size() == operation.data_length());
773 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
774 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
775 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700776 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700777 buffer_.begin(),
778 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700779
780 // Save the signature blob because if the update is interrupted after the
781 // download phase we don't go through this path anymore. Some alternatives to
782 // consider:
783 //
784 // 1. On resume, re-download the signature blob from the server and re-verify
785 // it.
786 //
787 // 2. Verify the signature as soon as it's received and don't checkpoint the
788 // blob and the signed sha-256 context.
789 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
790 string(&signatures_message_data_[0],
791 signatures_message_data_.size())))
792 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700793 // The hash of all data consumed so far should be verified against the signed
794 // hash.
795 signed_hash_context_ = hash_calculator_.GetContext();
796 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
797 signed_hash_context_))
798 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700799 LOG(INFO) << "Extracted signature data of size "
800 << manifest_.signatures_size() << " at "
801 << manifest_.signatures_offset();
802 return true;
803}
804
Jay Srinivasanf4318702012-09-24 11:56:24 -0700805ActionExitCode DeltaPerformer::ValidateMetadataSignature(
806 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700807
Jay Srinivasanf4318702012-09-24 11:56:24 -0700808 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800809 if (install_plan_->hash_checks_mandatory) {
810 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
811 return kActionCodeDownloadMetadataSignatureMissingError;
812 }
813
814 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700815 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700816 SendUmaStat(kActionCodeDownloadMetadataSignatureMissingError);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700817 return kActionCodeSuccess;
818 }
819
820 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700821 vector<char> metadata_signature;
822 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
823 &metadata_signature)) {
824 LOG(ERROR) << "Unable to decode base64 metadata signature: "
825 << install_plan_->metadata_signature;
826 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700827 }
828
Jay Srinivasanf4318702012-09-24 11:56:24 -0700829 vector<char> expected_metadata_hash;
830 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700831 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700832 &expected_metadata_hash)) {
833 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
834 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700835 }
836
Jay Srinivasanf4318702012-09-24 11:56:24 -0700837 OmahaHashCalculator metadata_hasher;
838 metadata_hasher.Update(metadata, metadata_size);
839 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700840 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700841 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700842 }
843
Jay Srinivasanf4318702012-09-24 11:56:24 -0700844 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
845 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
846 if (calculated_metadata_hash.empty()) {
847 LOG(ERROR) << "Computed actual hash of metadata is empty.";
848 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700849 }
850
Jay Srinivasanf4318702012-09-24 11:56:24 -0700851 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700852 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700853 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700854 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700855 utils::HexDumpVector(calculated_metadata_hash);
856 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700857 }
858
859 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
860 return kActionCodeSuccess;
861}
862
863ActionExitCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800864 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700865
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700866 if (!operation.data_sha256_hash().size()) {
867 if (!operation.data_length()) {
868 // Operations that do not have any data blob won't have any operation hash
869 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700870 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800871 // has already been validated. This is true for both HTTP and HTTPS cases.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700872 return kActionCodeSuccess;
873 }
874
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800875 // No hash is present for an operation that has data blobs. This shouldn't
876 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700877 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800878 // hashes. So if it happens it means either we've turned operation hash
879 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700880 // One caveat though: The last operation is a dummy signature operation
881 // that doesn't have a hash at the time the manifest is created. So we
882 // should not complaint about that operation. This operation can be
883 // recognized by the fact that it's offset is mentioned in the manifest.
884 if (manifest_.signatures_offset() &&
885 manifest_.signatures_offset() == operation.data_offset()) {
886 LOG(INFO) << "Skipping hash verification for signature operation "
887 << next_operation_num_ + 1;
888 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800889 if (install_plan_->hash_checks_mandatory) {
890 LOG(ERROR) << "Missing mandatory operation hash for operation "
891 << next_operation_num_ + 1;
892 return kActionCodeDownloadOperationHashMissingError;
893 }
894
895 // For non-mandatory cases, just send a UMA stat.
896 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
897 << " as there's no operation hash in manifest";
898 SendUmaStat(kActionCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700899 }
900 return kActionCodeSuccess;
901 }
902
903 vector<char> expected_op_hash;
904 expected_op_hash.assign(operation.data_sha256_hash().data(),
905 (operation.data_sha256_hash().data() +
906 operation.data_sha256_hash().size()));
907
908 OmahaHashCalculator operation_hasher;
909 operation_hasher.Update(&buffer_[0], operation.data_length());
910 if (!operation_hasher.Finalize()) {
911 LOG(ERROR) << "Unable to compute actual hash of operation "
912 << next_operation_num_;
913 return kActionCodeDownloadOperationHashVerificationError;
914 }
915
916 vector<char> calculated_op_hash = operation_hasher.raw_hash();
917 if (calculated_op_hash != expected_op_hash) {
918 LOG(ERROR) << "Hash verification failed for operation "
919 << next_operation_num_ << ". Expected hash = ";
920 utils::HexDumpVector(expected_op_hash);
921 LOG(ERROR) << "Calculated hash over " << operation.data_length()
922 << " bytes at offset: " << operation.data_offset() << " = ";
923 utils::HexDumpVector(calculated_op_hash);
924 return kActionCodeDownloadOperationHashMismatch;
925 }
926
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700927 return kActionCodeSuccess;
928}
929
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700930#define TEST_AND_RETURN_VAL(_retval, _condition) \
931 do { \
932 if (!(_condition)) { \
933 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
934 return _retval; \
935 } \
936 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700937
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700938ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700939 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700940 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700941 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700942
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700943 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700944 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700945 update_check_response_size ==
946 manifest_metadata_size_ + buffer_offset_);
947
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700948 // Verifies the payload hash.
949 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700950 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700951 !payload_hash_data.empty());
952 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
953 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700954
Darin Petkov437adc42010-10-07 13:12:24 -0700955 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700956 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700957 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700958 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700959 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700960 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
961 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700962 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700963 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
964 PayloadSigner::VerifySignature(
965 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700966 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700967 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700968 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700969 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
970 signed_hasher.SetContext(signed_hash_context_));
971 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
972 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700973 vector<char> hash_data = signed_hasher.raw_hash();
974 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700975 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
976 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700977 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700978 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700979 "Attached Signature:";
980 utils::HexDumpVector(signed_hash_data);
981 LOG(ERROR) << "Computed Signature:";
982 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700983 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700984 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800985
986 // At this point, we are guaranteed to have downloaded a full payload, i.e
987 // the one whose size matches the size mentioned in Omaha response. If any
988 // errors happen after this, it's likely a problem with the payload itself or
989 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800990 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800991 system_state_->payload_state()->DownloadComplete();
992
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700993 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700994}
995
Darin Petkov3aefa862010-12-07 14:45:00 -0800996bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
997 vector<char>* kernel_hash,
998 uint64_t* rootfs_size,
999 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001000 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1001 manifest_.has_new_kernel_info() &&
1002 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001003 *kernel_size = manifest_.new_kernel_info().size();
1004 *rootfs_size = manifest_.new_rootfs_info().size();
1005 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1006 manifest_.new_kernel_info().hash().end());
1007 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1008 manifest_.new_rootfs_info().hash().end());
1009 kernel_hash->swap(new_kernel_hash);
1010 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001011 return true;
1012}
1013
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001014namespace {
1015void LogVerifyError(bool is_kern,
1016 const string& local_hash,
1017 const string& expected_hash) {
1018 const char* type = is_kern ? "kernel" : "rootfs";
1019 LOG(ERROR) << "This is a server-side error due to "
1020 << "mismatched delta update image!";
1021 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1022 << "update that must be applied over a " << type << " with "
1023 << "a specific checksum, but the " << type << " we're starting "
1024 << "with doesn't have that checksum! This means that "
1025 << "the delta I've been given doesn't match my existing "
1026 << "system. The " << type << " partition I have has hash: "
1027 << local_hash << " but the update expected me to have "
1028 << expected_hash << " .";
1029 if (is_kern) {
1030 LOG(INFO) << "To get the checksum of a kernel partition on a "
1031 << "booted machine, run this command (change /dev/sda2 "
1032 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1033 << "openssl dgst -sha256 -binary | openssl base64";
1034 } else {
1035 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1036 << "booted machine, run this command (change /dev/sda3 "
1037 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1038 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1039 << "| sed 's/[^0-9]*//') / 256 )) | "
1040 << "openssl dgst -sha256 -binary | openssl base64";
1041 }
1042 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1043 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1044}
1045
1046string StringForHashBytes(const void* bytes, size_t size) {
1047 string ret;
1048 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1049 ret = "<unknown>";
1050 }
1051 return ret;
1052}
1053} // namespace
1054
Darin Petkov698d0412010-10-13 10:59:44 -07001055bool DeltaPerformer::VerifySourcePartitions() {
1056 LOG(INFO) << "Verifying source partitions.";
1057 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001058 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001059 if (manifest_.has_old_kernel_info()) {
1060 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001061 bool valid =
1062 !install_plan_->kernel_hash.empty() &&
1063 install_plan_->kernel_hash.size() == info.hash().size() &&
1064 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001065 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001066 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001067 if (!valid) {
1068 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001069 StringForHashBytes(install_plan_->kernel_hash.data(),
1070 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001071 StringForHashBytes(info.hash().data(),
1072 info.hash().size()));
1073 }
1074 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001075 }
1076 if (manifest_.has_old_rootfs_info()) {
1077 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001078 bool valid =
1079 !install_plan_->rootfs_hash.empty() &&
1080 install_plan_->rootfs_hash.size() == info.hash().size() &&
1081 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001082 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001083 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001084 if (!valid) {
1085 LogVerifyError(false,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001086 StringForHashBytes(install_plan_->kernel_hash.data(),
1087 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001088 StringForHashBytes(info.hash().data(),
1089 info.hash().size()));
1090 }
1091 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001092 }
1093 return true;
1094}
1095
Darin Petkov437adc42010-10-07 13:12:24 -07001096void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1097 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001098 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
1099}
1100
Darin Petkov0406e402010-10-06 21:33:11 -07001101bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1102 string update_check_response_hash) {
1103 int64_t next_operation = kUpdateStateOperationInvalid;
1104 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1105 &next_operation) &&
1106 next_operation != kUpdateStateOperationInvalid &&
1107 next_operation > 0);
1108
1109 string interrupted_hash;
1110 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1111 &interrupted_hash) &&
1112 !interrupted_hash.empty() &&
1113 interrupted_hash == update_check_response_hash);
1114
Darin Petkov61426142010-10-08 11:04:55 -07001115 int64_t resumed_update_failures;
1116 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1117 &resumed_update_failures) ||
1118 resumed_update_failures <= kMaxResumedUpdateFailures);
1119
Darin Petkov0406e402010-10-06 21:33:11 -07001120 // Sanity check the rest.
1121 int64_t next_data_offset = -1;
1122 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1123 &next_data_offset) &&
1124 next_data_offset >= 0);
1125
Darin Petkov437adc42010-10-07 13:12:24 -07001126 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001127 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001128 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1129 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001130
1131 int64_t manifest_metadata_size = 0;
1132 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1133 &manifest_metadata_size) &&
1134 manifest_metadata_size > 0);
1135
1136 return true;
1137}
1138
Darin Petkov9b230572010-10-08 10:20:09 -07001139bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001140 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1141 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001142 if (!quick) {
1143 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1144 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1145 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1146 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001147 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001148 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001149 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001150 }
Darin Petkov73058b42010-10-06 16:32:19 -07001151 return true;
1152}
1153
1154bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001155 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001156 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001157 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001158 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001159 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001160 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001161 hash_calculator_.GetContext()));
1162 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1163 buffer_offset_));
1164 last_updated_buffer_offset_ = buffer_offset_;
1165 }
Darin Petkov73058b42010-10-06 16:32:19 -07001166 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1167 next_operation_num_));
1168 return true;
1169}
1170
Darin Petkov9b230572010-10-08 10:20:09 -07001171bool DeltaPerformer::PrimeUpdateState() {
1172 CHECK(manifest_valid_);
1173 block_size_ = manifest_.block_size();
1174
1175 int64_t next_operation = kUpdateStateOperationInvalid;
1176 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1177 next_operation == kUpdateStateOperationInvalid ||
1178 next_operation <= 0) {
1179 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001180 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001181 return true;
1182 }
1183 next_operation_num_ = next_operation;
1184
1185 // Resuming an update -- load the rest of the update state.
1186 int64_t next_data_offset = -1;
1187 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1188 &next_data_offset) &&
1189 next_data_offset >= 0);
1190 buffer_offset_ = next_data_offset;
1191
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001192 // The signed hash context and the signature blob may be empty if the
1193 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001194 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1195 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001196 string signature_blob;
1197 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1198 signatures_message_data_.assign(signature_blob.begin(),
1199 signature_blob.end());
1200 }
Darin Petkov9b230572010-10-08 10:20:09 -07001201
1202 string hash_context;
1203 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1204 &hash_context) &&
1205 hash_calculator_.SetContext(hash_context));
1206
1207 int64_t manifest_metadata_size = 0;
1208 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1209 &manifest_metadata_size) &&
1210 manifest_metadata_size > 0);
1211 manifest_metadata_size_ = manifest_metadata_size;
1212
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001213 // Advance the download progress to reflect what doesn't need to be
1214 // re-downloaded.
1215 total_bytes_received_ += buffer_offset_;
1216
Darin Petkov61426142010-10-08 11:04:55 -07001217 // Speculatively count the resume as a failure.
1218 int64_t resumed_update_failures;
1219 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1220 resumed_update_failures++;
1221 } else {
1222 resumed_update_failures = 1;
1223 }
1224 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001225 return true;
1226}
1227
Jay Srinivasanedce2832012-10-24 18:57:47 -07001228void DeltaPerformer::SendUmaStat(ActionExitCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001229 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001230}
1231
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001232} // namespace chromeos_update_engine