blob: ae1f7e5e056b1e7f839643c124c7286372fa6b71 [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"
Jay Srinivasand29695d2013-04-08 15:08:05 -070021#include "update_engine/constants.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070023#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070024#include "update_engine/extent_writer.h"
25#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070026#include "update_engine/payload_signer.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080027#include "update_engine/payload_state_interface.h"
Darin Petkov73058b42010-10-06 16:32:19 -070028#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070029#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070030#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070031#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070032
33using std::min;
34using std::string;
35using std::vector;
36using google::protobuf::RepeatedPtrField;
37
38namespace chromeos_update_engine {
39
Jay Srinivasanf4318702012-09-24 11:56:24 -070040const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
41const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Darin Petkovabc7bc02011-02-23 14:39:43 -080042const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
43 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080044const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
45const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
46const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
47const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080048
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070049namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070050const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070051const int kMaxResumedUpdateFailures = 10;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070052// Opens path for read/write, put the fd into *fd. On success returns true
53// and sets *err to 0. On failure, returns false and sets *err to errno.
54bool OpenFile(const char* path, int* fd, int* err) {
55 if (*fd != -1) {
56 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
57 *err = EINVAL;
58 return false;
59 }
60 *fd = open(path, O_RDWR, 000);
61 if (*fd < 0) {
62 *err = errno;
63 PLOG(ERROR) << "Unable to open file " << path;
64 return false;
65 }
66 *err = 0;
67 return true;
68}
69
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070070} // namespace {}
71
Gilad Arnold8a86fa52013-01-15 12:35:05 -080072
73// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
74// arithmetic.
75static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
76 return part * norm / total;
77}
78
79void DeltaPerformer::LogProgress(const char* message_prefix) {
80 // Format operations total count and percentage.
81 string total_operations_str("?");
82 string completed_percentage_str("");
83 if (num_total_operations_) {
84 total_operations_str = StringPrintf("%zu", num_total_operations_);
85 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
86 completed_percentage_str =
87 StringPrintf(" (%llu%%)",
88 IntRatio(next_operation_num_, num_total_operations_,
89 100));
90 }
91
92 // Format download total count and percentage.
93 size_t payload_size = install_plan_->payload_size;
94 string payload_size_str("?");
95 string downloaded_percentage_str("");
96 if (payload_size) {
97 payload_size_str = StringPrintf("%zu", payload_size);
98 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
99 downloaded_percentage_str =
100 StringPrintf(" (%llu%%)",
101 IntRatio(total_bytes_received_, payload_size, 100));
102 }
103
104 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
105 << "/" << total_operations_str << " operations"
106 << completed_percentage_str << ", " << total_bytes_received_
107 << "/" << payload_size_str << " bytes downloaded"
108 << downloaded_percentage_str << ", overall progress "
109 << overall_progress_ << "%";
110}
111
112void DeltaPerformer::UpdateOverallProgress(bool force_log,
113 const char* message_prefix) {
114 // Compute our download and overall progress.
115 unsigned new_overall_progress = 0;
116 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
117 progress_weight_dont_add_up);
118 // Only consider download progress if its total size is known; otherwise
119 // adjust the operations weight to compensate for the absence of download
120 // progress. Also, make sure to cap the download portion at
121 // kProgressDownloadWeight, in case we end up downloading more than we
122 // initially expected (this indicates a problem, but could generally happen).
123 // TODO(garnold) the correction of operations weight when we do not have the
124 // total payload size, as well as the conditional guard below, should both be
125 // eliminated once we ensure that the payload_size in the install plan is
126 // always given and is non-zero. This currently isn't the case during unit
127 // tests (see chromium-os:37969).
128 size_t payload_size = install_plan_->payload_size;
129 unsigned actual_operations_weight = kProgressOperationsWeight;
130 if (payload_size)
131 new_overall_progress += min(
132 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
133 kProgressDownloadWeight)),
134 kProgressDownloadWeight);
135 else
136 actual_operations_weight += kProgressDownloadWeight;
137
138 // Only add completed operations if their total number is known; we definitely
139 // expect an update to have at least one operation, so the expectation is that
140 // this will eventually reach |actual_operations_weight|.
141 if (num_total_operations_)
142 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
143 actual_operations_weight);
144
145 // Progress ratio cannot recede, unless our assumptions about the total
146 // payload size, total number of operations, or the monotonicity of progress
147 // is breached.
148 if (new_overall_progress < overall_progress_) {
149 LOG(WARNING) << "progress counter receded from " << overall_progress_
150 << "% down to " << new_overall_progress << "%; this is a bug";
151 force_log = true;
152 }
153 overall_progress_ = new_overall_progress;
154
155 // Update chunk index, log as needed: if forced by called, or we completed a
156 // progress chunk, or a timeout has expired.
157 base::Time curr_time = base::Time::Now();
158 unsigned curr_progress_chunk =
159 overall_progress_ * kProgressLogMaxChunks / 100;
160 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
161 curr_time > forced_progress_log_time_) {
162 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
163 LogProgress(message_prefix);
164 }
165 last_progress_chunk_ = curr_progress_chunk;
166}
167
168
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700169// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
170// it safely. Returns false otherwise.
171bool DeltaPerformer::IsIdempotentOperation(
172 const DeltaArchiveManifest_InstallOperation& op) {
173 if (op.src_extents_size() == 0) {
174 return true;
175 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700176 // When in doubt, it's safe to declare an op non-idempotent. Note that we
177 // could detect other types of idempotent operations here such as a MOVE that
178 // moves blocks onto themselves. However, we rely on the server to not send
179 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700180 ExtentRanges src_ranges;
181 src_ranges.AddRepeatedExtents(op.src_extents());
182 const uint64_t block_count = src_ranges.blocks();
183 src_ranges.SubtractRepeatedExtents(op.dst_extents());
184 return block_count == src_ranges.blocks();
185}
186
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700187int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700188 int err;
189 if (OpenFile(path, &fd_, &err))
190 path_ = path;
191 return -err;
192}
193
194bool DeltaPerformer::OpenKernel(const char* kernel_path) {
195 int err;
196 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
197 if (success)
198 kernel_path_ = kernel_path;
199 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700200}
201
202int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700203 int err = 0;
204 if (close(kernel_fd_) == -1) {
205 err = errno;
206 PLOG(ERROR) << "Unable to close kernel fd:";
207 }
208 if (close(fd_) == -1) {
209 err = errno;
210 PLOG(ERROR) << "Unable to close rootfs fd:";
211 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700212 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800213 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700214 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800215 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700216 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
217 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800218 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800219 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700220 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700221}
222
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700223namespace {
224
225void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
226 string sha256;
227 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
228 info.hash().size(),
229 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800230 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
231 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700232 } else {
233 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
234 }
235}
236
237void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
238 if (manifest.has_old_kernel_info())
239 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
240 if (manifest.has_old_rootfs_info())
241 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
242 if (manifest.has_new_kernel_info())
243 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
244 if (manifest.has_new_rootfs_info())
245 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
246}
247
248} // namespace {}
249
Jay Srinivasanf4318702012-09-24 11:56:24 -0700250uint64_t DeltaPerformer::GetManifestSizeOffset() {
251 // Manifest size is stored right after the magic string and the version.
252 return strlen(kDeltaMagic) + kDeltaVersionSize;
253}
254
255uint64_t DeltaPerformer::GetManifestOffset() {
256 // Actual manifest begins right after the manifest size field.
257 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
258}
259
260
Darin Petkov9574f7e2011-01-13 10:48:12 -0800261DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
262 const std::vector<char>& payload,
263 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700264 uint64_t* metadata_size,
265 ActionExitCode* error) {
266 *error = kActionCodeSuccess;
267
Jay Srinivasanf4318702012-09-24 11:56:24 -0700268 // manifest_offset is the byte offset where the manifest protobuf begins.
269 const uint64_t manifest_offset = GetManifestOffset();
270 if (payload.size() < manifest_offset) {
271 // Don't have enough bytes to even know the manifest size.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800272 return kMetadataParseInsufficientData;
273 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700274
Jay Srinivasanf4318702012-09-24 11:56:24 -0700275 // Validate the magic string.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800276 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
277 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700278 *error = kActionCodeDownloadInvalidMetadataMagicString;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800279 return kMetadataParseError;
280 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700281
282 // TODO(jaysri): Compare the version number and skip unknown manifest
283 // versions. We don't check the version at all today.
284
Jay Srinivasanf4318702012-09-24 11:56:24 -0700285 // Next, parse the manifest size.
286 uint64_t manifest_size;
287 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
288 manifest_size_size_mismatch);
289 memcpy(&manifest_size,
290 &payload[GetManifestSizeOffset()],
291 kDeltaManifestSizeSize);
292 manifest_size = be64toh(manifest_size); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700293
294 // Now, check if the metasize we computed matches what was passed in
295 // through Omaha Response.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700296 *metadata_size = manifest_offset + manifest_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700297
Jay Srinivasanf4318702012-09-24 11:56:24 -0700298 // If the metadata size is present in install plan, check for it immediately
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700299 // even before waiting for that many number of bytes to be downloaded
300 // in the payload. This will prevent any attack which relies on us downloading
Jay Srinivasanf4318702012-09-24 11:56:24 -0700301 // data beyond the expected metadata size.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800302 if (install_plan_->hash_checks_mandatory) {
303 if (install_plan_->metadata_size != *metadata_size) {
304 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
305 << install_plan_->metadata_size << ") is missing/incorrect."
306 << ", Actual = " << *metadata_size;
307 *error = kActionCodeDownloadInvalidMetadataSize;
308 return kMetadataParseError;
309 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700310 }
311
312 // Now that we have validated the metadata size, we should wait for the full
313 // metadata to be read in before we can parse it.
314 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800315 return kMetadataParseInsufficientData;
316 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700317
318 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700319 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700320 // that we just log once (instead of logging n times) if it takes n
321 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800322 if (install_plan_->metadata_size == *metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700323 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800324 } else {
325 // For mandatory-cases, we'd have already returned a kMetadataParseError
326 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
327 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
328 << install_plan_->metadata_size
329 << ") in Omaha response as validation is not mandatory. "
330 << "Trusting metadata size in payload = " << *metadata_size;
331 SendUmaStat(kActionCodeDownloadInvalidMetadataSize);
332 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700333
Jay Srinivasanf4318702012-09-24 11:56:24 -0700334 // We have the full metadata in |payload|. Verify its integrity
335 // and authenticity based on the information we have in Omaha response.
336 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700337 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800338 if (install_plan_->hash_checks_mandatory) {
339 LOG(ERROR) << "Mandatory metadata signature validation failed";
340 return kMetadataParseError;
341 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700342
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800343 // For non-mandatory cases, just send a UMA stat.
344 LOG(WARNING) << "Ignoring metadata signature validation failures";
345 SendUmaStat(*error);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700346 *error = kActionCodeSuccess;
347 }
348
Jay Srinivasanf4318702012-09-24 11:56:24 -0700349 // The metadata in |payload| is deemed valid. So, it's now safe to
350 // parse the protobuf.
351 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800352 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700353 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800354 return kMetadataParseError;
355 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800356 return kMetadataParseSuccess;
357}
358
359
Don Garrette410e0f2011-11-10 15:39:01 -0800360// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800361// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700362// and stores an action exit code in |error|.
363bool DeltaPerformer::Write(const void* bytes, size_t count,
364 ActionExitCode *error) {
365 *error = kActionCodeSuccess;
366
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700367 const char* c_bytes = reinterpret_cast<const char*>(bytes);
368 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800369 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800370
371 // Update the total byte downloaded count and the progress logs.
372 total_bytes_received_ += count;
373 UpdateOverallProgress(false, "Completed ");
374
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700375 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800376 MetadataParseResult result = ParsePayloadMetadata(buffer_,
377 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700378 &manifest_metadata_size_,
379 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800380 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800381 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800382 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800383 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800384 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700385 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700386 // Remove protobuf and header info from buffer_, so buffer_ contains
387 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700388 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700389 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700390 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700391 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700392 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700393
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700394 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700395 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700396 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700397 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800398 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700399 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800400
401 num_rootfs_operations_ = manifest_.install_operations_size();
402 num_total_operations_ =
403 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
404 if (next_operation_num_ > 0)
405 UpdateOverallProgress(true, "Resuming after ");
406 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700407 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800408
409 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700410 // Check if we should cancel the current attempt for any reason.
411 // In this case, *error will have already been populated with the reason
412 // why we're cancelling.
413 if (system_state_->update_attempter()->ShouldCancel(error))
414 return false;
415
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800416 const bool is_kernel_partition =
417 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700418 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800419 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700420 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800421 next_operation_num_ - num_rootfs_operations_) :
422 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700423 if (!CanPerformInstallOperation(op)) {
424 // This means we don't have enough bytes received yet to carry out the
425 // next operation.
426 return true;
427 }
428
Jay Srinivasanf4318702012-09-24 11:56:24 -0700429 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700430 // Otherwise, keep the old behavior. This serves as a knob to disable
431 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800432 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
433 // we would have already failed in ParsePayloadMetadata method and thus not
434 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700435 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700436 // Note: Validate must be called only if CanPerformInstallOperation is
437 // called. Otherwise, we might be failing operations before even if there
438 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800439 *error = ValidateOperationHash(op);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700440 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800441 if (install_plan_->hash_checks_mandatory) {
442 LOG(ERROR) << "Mandatory operation hash check failed";
443 return false;
444 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700445
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800446 // For non-mandatory cases, just send a UMA stat.
447 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700448 SendUmaStat(*error);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800449 *error = kActionCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700450 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700451 }
452
Darin Petkov45580e42010-10-08 14:02:40 -0700453 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700454 ScopedTerminatorExitUnblocker exit_unblocker =
455 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700456 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700457 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
458 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700459 if (!PerformReplaceOperation(op, is_kernel_partition)) {
460 LOG(ERROR) << "Failed to perform replace operation "
461 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700462 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800463 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700464 }
465 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700466 if (!PerformMoveOperation(op, is_kernel_partition)) {
467 LOG(ERROR) << "Failed to perform move operation "
468 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700469 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800470 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700471 }
472 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700473 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
474 LOG(ERROR) << "Failed to perform bsdiff operation "
475 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700476 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800477 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700478 }
479 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800480
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700481 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800482 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700483 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700484 }
Don Garrette410e0f2011-11-10 15:39:01 -0800485 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700486}
487
488bool DeltaPerformer::CanPerformInstallOperation(
489 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
490 operation) {
491 // Move operations don't require any data blob, so they can always
492 // be performed
493 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
494 return true;
495
496 // See if we have the entire data blob in the buffer
497 if (operation.data_offset() < buffer_offset_) {
498 LOG(ERROR) << "we threw away data it seems?";
499 return false;
500 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700501
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700502 return (operation.data_offset() + operation.data_length()) <=
503 (buffer_offset_ + buffer_.size());
504}
505
506bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700507 const DeltaArchiveManifest_InstallOperation& operation,
508 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700509 CHECK(operation.type() == \
510 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
511 operation.type() == \
512 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
513
514 // Since we delete data off the beginning of the buffer as we use it,
515 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700516 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
517 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700518
Darin Petkov437adc42010-10-07 13:12:24 -0700519 // Extract the signature message if it's in this operation.
520 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700521
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700522 DirectExtentWriter direct_writer;
523 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
524 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700525
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700526 // Since bzip decompression is optional, we have a variable writer that will
527 // point to one of the ExtentWriter objects above.
528 ExtentWriter* writer = NULL;
529 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
530 writer = &zero_pad_writer;
531 } else if (operation.type() ==
532 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
533 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
534 writer = bzip_writer.get();
535 } else {
536 NOTREACHED();
537 }
538
539 // Create a vector of extents to pass to the ExtentWriter.
540 vector<Extent> extents;
541 for (int i = 0; i < operation.dst_extents_size(); i++) {
542 extents.push_back(operation.dst_extents(i));
543 }
544
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700545 int fd = is_kernel_partition ? kernel_fd_ : fd_;
546
547 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700548 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
549 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700550
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700551 // Update buffer
552 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700553 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700554 return true;
555}
556
557bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700558 const DeltaArchiveManifest_InstallOperation& operation,
559 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700560 // Calculate buffer size. Note, this function doesn't do a sliding
561 // window to copy in case the source and destination blocks overlap.
562 // If we wanted to do a sliding window, we could program the server
563 // to generate deltas that effectively did a sliding window.
564
565 uint64_t blocks_to_read = 0;
566 for (int i = 0; i < operation.src_extents_size(); i++)
567 blocks_to_read += operation.src_extents(i).num_blocks();
568
569 uint64_t blocks_to_write = 0;
570 for (int i = 0; i < operation.dst_extents_size(); i++)
571 blocks_to_write += operation.dst_extents(i).num_blocks();
572
573 DCHECK_EQ(blocks_to_write, blocks_to_read);
574 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700575
576 int fd = is_kernel_partition ? kernel_fd_ : fd_;
577
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700578 // Read in bytes.
579 ssize_t bytes_read = 0;
580 for (int i = 0; i < operation.src_extents_size(); i++) {
581 ssize_t bytes_read_this_iteration = 0;
582 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200583 const size_t bytes = extent.num_blocks() * block_size_;
584 if (extent.start_block() == kSparseHole) {
585 bytes_read_this_iteration = bytes;
586 memset(&buf[bytes_read], 0, bytes);
587 } else {
588 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
589 &buf[bytes_read],
590 bytes,
591 extent.start_block() * block_size_,
592 &bytes_read_this_iteration));
593 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700594 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200595 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700596 bytes_read += bytes_read_this_iteration;
597 }
598
Darin Petkov45580e42010-10-08 14:02:40 -0700599 // If this is a non-idempotent operation, request a delayed exit and clear the
600 // update state in case the operation gets interrupted. Do this as late as
601 // possible.
602 if (!IsIdempotentOperation(operation)) {
603 Terminator::set_exit_blocked(true);
604 ResetUpdateProgress(prefs_, true);
605 }
606
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700607 // Write bytes out.
608 ssize_t bytes_written = 0;
609 for (int i = 0; i < operation.dst_extents_size(); i++) {
610 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200611 const size_t bytes = extent.num_blocks() * block_size_;
612 if (extent.start_block() == kSparseHole) {
613 DCHECK_EQ(&buf[bytes_written],
614 std::search_n(&buf[bytes_written], &buf[bytes_written + bytes],
615 bytes, 0));
616 } else {
617 TEST_AND_RETURN_FALSE(
618 utils::PWriteAll(fd,
619 &buf[bytes_written],
620 bytes,
621 extent.start_block() * block_size_));
622 }
623 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700624 }
625 DCHECK_EQ(bytes_written, bytes_read);
626 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
627 return true;
628}
629
630bool DeltaPerformer::ExtentsToBsdiffPositionsString(
631 const RepeatedPtrField<Extent>& extents,
632 uint64_t block_size,
633 uint64_t full_length,
634 string* positions_string) {
635 string ret;
636 uint64_t length = 0;
637 for (int i = 0; i < extents.size(); i++) {
638 Extent extent = extents.Get(i);
639 int64_t start = extent.start_block();
640 uint64_t this_length = min(full_length - length,
641 extent.num_blocks() * block_size);
642 if (start == static_cast<int64_t>(kSparseHole))
643 start = -1;
644 else
645 start *= block_size;
646 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
647 length += this_length;
648 }
649 TEST_AND_RETURN_FALSE(length == full_length);
650 if (!ret.empty())
651 ret.resize(ret.size() - 1); // Strip trailing comma off
652 *positions_string = ret;
653 return true;
654}
655
656bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700657 const DeltaArchiveManifest_InstallOperation& operation,
658 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700659 // Since we delete data off the beginning of the buffer as we use it,
660 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700661 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
662 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700663
664 string input_positions;
665 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
666 block_size_,
667 operation.src_length(),
668 &input_positions));
669 string output_positions;
670 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
671 block_size_,
672 operation.dst_length(),
673 &output_positions));
674
675 string temp_filename;
676 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
677 &temp_filename,
678 NULL));
679 ScopedPathUnlinker path_unlinker(temp_filename);
680 {
681 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
682 ScopedFdCloser fd_closer(&fd);
683 TEST_AND_RETURN_FALSE(
684 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
685 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700686
Darin Petkov7f2ec752013-04-03 14:45:19 +0200687 // Update the buffer to release the patch data memory as soon as the patch
688 // file is written out.
689 buffer_offset_ += operation.data_length();
690 DiscardBufferHeadBytes(operation.data_length());
691
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700692 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700693 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700694
Darin Petkov45580e42010-10-08 14:02:40 -0700695 // If this is a non-idempotent operation, request a delayed exit and clear the
696 // update state in case the operation gets interrupted. Do this as late as
697 // possible.
698 if (!IsIdempotentOperation(operation)) {
699 Terminator::set_exit_blocked(true);
700 ResetUpdateProgress(prefs_, true);
701 }
702
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700703 vector<string> cmd;
704 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700705 cmd.push_back(path);
706 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700707 cmd.push_back(temp_filename);
708 cmd.push_back(input_positions);
709 cmd.push_back(output_positions);
710 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700711 TEST_AND_RETURN_FALSE(
712 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700713 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700714 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700715 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700716 TEST_AND_RETURN_FALSE(return_code == 0);
717
718 if (operation.dst_length() % block_size_) {
719 // Zero out rest of final block.
720 // TODO(adlr): build this into bspatch; it's more efficient that way.
721 const Extent& last_extent =
722 operation.dst_extents(operation.dst_extents_size() - 1);
723 const uint64_t end_byte =
724 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
725 const uint64_t begin_byte =
726 end_byte - (block_size_ - operation.dst_length() % block_size_);
727 vector<char> zeros(end_byte - begin_byte);
728 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700729 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700730 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700731 return true;
732}
733
Darin Petkovd7061ab2010-10-06 14:37:09 -0700734bool DeltaPerformer::ExtractSignatureMessage(
735 const DeltaArchiveManifest_InstallOperation& operation) {
736 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
737 !manifest_.has_signatures_offset() ||
738 manifest_.signatures_offset() != operation.data_offset()) {
739 return false;
740 }
741 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
742 manifest_.signatures_size() == operation.data_length());
743 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
744 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
745 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700746 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700747 buffer_.begin(),
748 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700749
750 // Save the signature blob because if the update is interrupted after the
751 // download phase we don't go through this path anymore. Some alternatives to
752 // consider:
753 //
754 // 1. On resume, re-download the signature blob from the server and re-verify
755 // it.
756 //
757 // 2. Verify the signature as soon as it's received and don't checkpoint the
758 // blob and the signed sha-256 context.
759 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
760 string(&signatures_message_data_[0],
761 signatures_message_data_.size())))
762 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700763 // The hash of all data consumed so far should be verified against the signed
764 // hash.
765 signed_hash_context_ = hash_calculator_.GetContext();
766 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
767 signed_hash_context_))
768 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700769 LOG(INFO) << "Extracted signature data of size "
770 << manifest_.signatures_size() << " at "
771 << manifest_.signatures_offset();
772 return true;
773}
774
Jay Srinivasanf4318702012-09-24 11:56:24 -0700775ActionExitCode DeltaPerformer::ValidateMetadataSignature(
776 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700777
Jay Srinivasanf4318702012-09-24 11:56:24 -0700778 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800779 if (install_plan_->hash_checks_mandatory) {
780 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
781 return kActionCodeDownloadMetadataSignatureMissingError;
782 }
783
784 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700785 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700786 SendUmaStat(kActionCodeDownloadMetadataSignatureMissingError);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700787 return kActionCodeSuccess;
788 }
789
790 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700791 vector<char> metadata_signature;
792 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
793 &metadata_signature)) {
794 LOG(ERROR) << "Unable to decode base64 metadata signature: "
795 << install_plan_->metadata_signature;
796 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700797 }
798
Jay Srinivasanf4318702012-09-24 11:56:24 -0700799 vector<char> expected_metadata_hash;
800 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700801 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700802 &expected_metadata_hash)) {
803 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
804 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700805 }
806
Jay Srinivasanf4318702012-09-24 11:56:24 -0700807 OmahaHashCalculator metadata_hasher;
808 metadata_hasher.Update(metadata, metadata_size);
809 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700810 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700811 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700812 }
813
Jay Srinivasanf4318702012-09-24 11:56:24 -0700814 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
815 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
816 if (calculated_metadata_hash.empty()) {
817 LOG(ERROR) << "Computed actual hash of metadata is empty.";
818 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700819 }
820
Jay Srinivasanf4318702012-09-24 11:56:24 -0700821 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700822 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700823 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700824 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700825 utils::HexDumpVector(calculated_metadata_hash);
826 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700827 }
828
829 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
830 return kActionCodeSuccess;
831}
832
833ActionExitCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800834 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700835
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700836 if (!operation.data_sha256_hash().size()) {
837 if (!operation.data_length()) {
838 // Operations that do not have any data blob won't have any operation hash
839 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700840 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800841 // has already been validated. This is true for both HTTP and HTTPS cases.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700842 return kActionCodeSuccess;
843 }
844
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800845 // No hash is present for an operation that has data blobs. This shouldn't
846 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700847 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800848 // hashes. So if it happens it means either we've turned operation hash
849 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700850 // One caveat though: The last operation is a dummy signature operation
851 // that doesn't have a hash at the time the manifest is created. So we
852 // should not complaint about that operation. This operation can be
853 // recognized by the fact that it's offset is mentioned in the manifest.
854 if (manifest_.signatures_offset() &&
855 manifest_.signatures_offset() == operation.data_offset()) {
856 LOG(INFO) << "Skipping hash verification for signature operation "
857 << next_operation_num_ + 1;
858 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800859 if (install_plan_->hash_checks_mandatory) {
860 LOG(ERROR) << "Missing mandatory operation hash for operation "
861 << next_operation_num_ + 1;
862 return kActionCodeDownloadOperationHashMissingError;
863 }
864
865 // For non-mandatory cases, just send a UMA stat.
866 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
867 << " as there's no operation hash in manifest";
868 SendUmaStat(kActionCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700869 }
870 return kActionCodeSuccess;
871 }
872
873 vector<char> expected_op_hash;
874 expected_op_hash.assign(operation.data_sha256_hash().data(),
875 (operation.data_sha256_hash().data() +
876 operation.data_sha256_hash().size()));
877
878 OmahaHashCalculator operation_hasher;
879 operation_hasher.Update(&buffer_[0], operation.data_length());
880 if (!operation_hasher.Finalize()) {
881 LOG(ERROR) << "Unable to compute actual hash of operation "
882 << next_operation_num_;
883 return kActionCodeDownloadOperationHashVerificationError;
884 }
885
886 vector<char> calculated_op_hash = operation_hasher.raw_hash();
887 if (calculated_op_hash != expected_op_hash) {
888 LOG(ERROR) << "Hash verification failed for operation "
889 << next_operation_num_ << ". Expected hash = ";
890 utils::HexDumpVector(expected_op_hash);
891 LOG(ERROR) << "Calculated hash over " << operation.data_length()
892 << " bytes at offset: " << operation.data_offset() << " = ";
893 utils::HexDumpVector(calculated_op_hash);
894 return kActionCodeDownloadOperationHashMismatch;
895 }
896
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700897 return kActionCodeSuccess;
898}
899
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700900#define TEST_AND_RETURN_VAL(_retval, _condition) \
901 do { \
902 if (!(_condition)) { \
903 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
904 return _retval; \
905 } \
906 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700907
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700908ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700909 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700910 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700911 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700912
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700913 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700914 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700915 update_check_response_size ==
916 manifest_metadata_size_ + buffer_offset_);
917
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700918 // Verifies the payload hash.
919 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700920 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700921 !payload_hash_data.empty());
922 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
923 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700924
Darin Petkov437adc42010-10-07 13:12:24 -0700925 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700926 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700927 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700928 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700929 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700930 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
931 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700932 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700933 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
934 PayloadSigner::VerifySignature(
935 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700936 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700937 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700938 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700939 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
940 signed_hasher.SetContext(signed_hash_context_));
941 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
942 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700943 vector<char> hash_data = signed_hasher.raw_hash();
944 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700945 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
946 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700947 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700948 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700949 "Attached Signature:";
950 utils::HexDumpVector(signed_hash_data);
951 LOG(ERROR) << "Computed Signature:";
952 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700953 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700954 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800955
956 // At this point, we are guaranteed to have downloaded a full payload, i.e
957 // the one whose size matches the size mentioned in Omaha response. If any
958 // errors happen after this, it's likely a problem with the payload itself or
959 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800960 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800961 system_state_->payload_state()->DownloadComplete();
962
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700963 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700964}
965
Darin Petkov3aefa862010-12-07 14:45:00 -0800966bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
967 vector<char>* kernel_hash,
968 uint64_t* rootfs_size,
969 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700970 TEST_AND_RETURN_FALSE(manifest_valid_ &&
971 manifest_.has_new_kernel_info() &&
972 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -0800973 *kernel_size = manifest_.new_kernel_info().size();
974 *rootfs_size = manifest_.new_rootfs_info().size();
975 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
976 manifest_.new_kernel_info().hash().end());
977 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
978 manifest_.new_rootfs_info().hash().end());
979 kernel_hash->swap(new_kernel_hash);
980 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700981 return true;
982}
983
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -0700984namespace {
985void LogVerifyError(bool is_kern,
986 const string& local_hash,
987 const string& expected_hash) {
988 const char* type = is_kern ? "kernel" : "rootfs";
989 LOG(ERROR) << "This is a server-side error due to "
990 << "mismatched delta update image!";
991 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
992 << "update that must be applied over a " << type << " with "
993 << "a specific checksum, but the " << type << " we're starting "
994 << "with doesn't have that checksum! This means that "
995 << "the delta I've been given doesn't match my existing "
996 << "system. The " << type << " partition I have has hash: "
997 << local_hash << " but the update expected me to have "
998 << expected_hash << " .";
999 if (is_kern) {
1000 LOG(INFO) << "To get the checksum of a kernel partition on a "
1001 << "booted machine, run this command (change /dev/sda2 "
1002 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1003 << "openssl dgst -sha256 -binary | openssl base64";
1004 } else {
1005 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1006 << "booted machine, run this command (change /dev/sda3 "
1007 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1008 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1009 << "| sed 's/[^0-9]*//') / 256 )) | "
1010 << "openssl dgst -sha256 -binary | openssl base64";
1011 }
1012 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1013 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1014}
1015
1016string StringForHashBytes(const void* bytes, size_t size) {
1017 string ret;
1018 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1019 ret = "<unknown>";
1020 }
1021 return ret;
1022}
1023} // namespace
1024
Darin Petkov698d0412010-10-13 10:59:44 -07001025bool DeltaPerformer::VerifySourcePartitions() {
1026 LOG(INFO) << "Verifying source partitions.";
1027 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001028 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001029 if (manifest_.has_old_kernel_info()) {
1030 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001031 bool valid =
1032 !install_plan_->kernel_hash.empty() &&
1033 install_plan_->kernel_hash.size() == info.hash().size() &&
1034 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001035 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001036 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001037 if (!valid) {
1038 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001039 StringForHashBytes(install_plan_->kernel_hash.data(),
1040 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001041 StringForHashBytes(info.hash().data(),
1042 info.hash().size()));
1043 }
1044 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001045 }
1046 if (manifest_.has_old_rootfs_info()) {
1047 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001048 bool valid =
1049 !install_plan_->rootfs_hash.empty() &&
1050 install_plan_->rootfs_hash.size() == info.hash().size() &&
1051 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001052 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001053 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001054 if (!valid) {
1055 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001056 StringForHashBytes(install_plan_->rootfs_hash.data(),
1057 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001058 StringForHashBytes(info.hash().data(),
1059 info.hash().size()));
1060 }
1061 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001062 }
1063 return true;
1064}
1065
Darin Petkov437adc42010-10-07 13:12:24 -07001066void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1067 hash_calculator_.Update(&buffer_[0], count);
Darin Petkov7f2ec752013-04-03 14:45:19 +02001068 // Copy the remainder data into a temporary vector first to ensure that any
1069 // unused memory in the updated |buffer_| will be released.
1070 vector<char> temp(buffer_.begin() + count, buffer_.end());
1071 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001072}
1073
Darin Petkov0406e402010-10-06 21:33:11 -07001074bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1075 string update_check_response_hash) {
1076 int64_t next_operation = kUpdateStateOperationInvalid;
1077 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1078 &next_operation) &&
1079 next_operation != kUpdateStateOperationInvalid &&
1080 next_operation > 0);
1081
1082 string interrupted_hash;
1083 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1084 &interrupted_hash) &&
1085 !interrupted_hash.empty() &&
1086 interrupted_hash == update_check_response_hash);
1087
Darin Petkov61426142010-10-08 11:04:55 -07001088 int64_t resumed_update_failures;
1089 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1090 &resumed_update_failures) ||
1091 resumed_update_failures <= kMaxResumedUpdateFailures);
1092
Darin Petkov0406e402010-10-06 21:33:11 -07001093 // Sanity check the rest.
1094 int64_t next_data_offset = -1;
1095 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1096 &next_data_offset) &&
1097 next_data_offset >= 0);
1098
Darin Petkov437adc42010-10-07 13:12:24 -07001099 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001100 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001101 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1102 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001103
1104 int64_t manifest_metadata_size = 0;
1105 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1106 &manifest_metadata_size) &&
1107 manifest_metadata_size > 0);
1108
1109 return true;
1110}
1111
Darin Petkov9b230572010-10-08 10:20:09 -07001112bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001113 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1114 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001115 if (!quick) {
1116 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1117 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1118 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1119 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001120 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001121 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001122 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001123 }
Darin Petkov73058b42010-10-06 16:32:19 -07001124 return true;
1125}
1126
1127bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001128 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001129 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001130 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001131 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001132 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001133 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001134 hash_calculator_.GetContext()));
1135 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1136 buffer_offset_));
1137 last_updated_buffer_offset_ = buffer_offset_;
1138 }
Darin Petkov73058b42010-10-06 16:32:19 -07001139 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1140 next_operation_num_));
1141 return true;
1142}
1143
Darin Petkov9b230572010-10-08 10:20:09 -07001144bool DeltaPerformer::PrimeUpdateState() {
1145 CHECK(manifest_valid_);
1146 block_size_ = manifest_.block_size();
1147
1148 int64_t next_operation = kUpdateStateOperationInvalid;
1149 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1150 next_operation == kUpdateStateOperationInvalid ||
1151 next_operation <= 0) {
1152 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001153 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001154 return true;
1155 }
1156 next_operation_num_ = next_operation;
1157
1158 // Resuming an update -- load the rest of the update state.
1159 int64_t next_data_offset = -1;
1160 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1161 &next_data_offset) &&
1162 next_data_offset >= 0);
1163 buffer_offset_ = next_data_offset;
1164
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001165 // The signed hash context and the signature blob may be empty if the
1166 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001167 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1168 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001169 string signature_blob;
1170 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1171 signatures_message_data_.assign(signature_blob.begin(),
1172 signature_blob.end());
1173 }
Darin Petkov9b230572010-10-08 10:20:09 -07001174
1175 string hash_context;
1176 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1177 &hash_context) &&
1178 hash_calculator_.SetContext(hash_context));
1179
1180 int64_t manifest_metadata_size = 0;
1181 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1182 &manifest_metadata_size) &&
1183 manifest_metadata_size > 0);
1184 manifest_metadata_size_ = manifest_metadata_size;
1185
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001186 // Advance the download progress to reflect what doesn't need to be
1187 // re-downloaded.
1188 total_bytes_received_ += buffer_offset_;
1189
Darin Petkov61426142010-10-08 11:04:55 -07001190 // Speculatively count the resume as a failure.
1191 int64_t resumed_update_failures;
1192 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1193 resumed_update_failures++;
1194 } else {
1195 resumed_update_failures = 1;
1196 }
1197 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001198 return true;
1199}
1200
Jay Srinivasanedce2832012-10-24 18:57:47 -07001201void DeltaPerformer::SendUmaStat(ActionExitCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001202 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001203}
1204
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001205} // namespace chromeos_update_engine