blob: 56158010ed65d24980aa2e273a289bfcdf2cfc01 [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,
David Zeuthena99981f2013-04-29 13:42:47 -0700265 ErrorCode* error) {
266 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700267
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.";
David Zeuthena99981f2013-04-29 13:42:47 -0700278 *error = kErrorCodeDownloadInvalidMetadataMagicString;
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;
David Zeuthena99981f2013-04-29 13:42:47 -0700307 *error = kErrorCodeDownloadInvalidMetadataSize;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800308 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;
David Zeuthena99981f2013-04-29 13:42:47 -0700331 SendUmaStat(kErrorCodeDownloadInvalidMetadataSize);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800332 }
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);
David Zeuthena99981f2013-04-29 13:42:47 -0700337 if (*error != kErrorCodeSuccess) {
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);
David Zeuthena99981f2013-04-29 13:42:47 -0700346 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700347 }
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.";
David Zeuthena99981f2013-04-29 13:42:47 -0700353 *error = kErrorCodeDownloadManifestParseError;
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,
David Zeuthena99981f2013-04-29 13:42:47 -0700364 ErrorCode *error) {
365 *error = kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700366
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 }
Gilad Arnold21504f02013-05-24 08:51:22 -0700386
387 // Checks the integrity of the payload manifest.
388 if ((*error = ValidateManifest()) != kErrorCodeSuccess)
389 return false;
390
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700391 // Remove protobuf and header info from buffer_, so buffer_ contains
392 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700393 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700394 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700395 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700396 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700397 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700398
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700399 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700400 if (!PrimeUpdateState()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700401 *error = kErrorCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700402 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800403 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700404 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800405
406 num_rootfs_operations_ = manifest_.install_operations_size();
407 num_total_operations_ =
408 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
409 if (next_operation_num_ > 0)
410 UpdateOverallProgress(true, "Resuming after ");
411 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700412 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800413
414 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700415 // Check if we should cancel the current attempt for any reason.
416 // In this case, *error will have already been populated with the reason
417 // why we're cancelling.
418 if (system_state_->update_attempter()->ShouldCancel(error))
419 return false;
420
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800421 const bool is_kernel_partition =
422 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700423 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800424 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700425 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800426 next_operation_num_ - num_rootfs_operations_) :
427 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700428 if (!CanPerformInstallOperation(op)) {
429 // This means we don't have enough bytes received yet to carry out the
430 // next operation.
431 return true;
432 }
433
Jay Srinivasanf4318702012-09-24 11:56:24 -0700434 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700435 // Otherwise, keep the old behavior. This serves as a knob to disable
436 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800437 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
438 // we would have already failed in ParsePayloadMetadata method and thus not
439 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700440 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700441 // Note: Validate must be called only if CanPerformInstallOperation is
442 // called. Otherwise, we might be failing operations before even if there
443 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800444 *error = ValidateOperationHash(op);
David Zeuthena99981f2013-04-29 13:42:47 -0700445 if (*error != kErrorCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800446 if (install_plan_->hash_checks_mandatory) {
447 LOG(ERROR) << "Mandatory operation hash check failed";
448 return false;
449 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700450
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800451 // For non-mandatory cases, just send a UMA stat.
452 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700453 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700454 *error = kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700455 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700456 }
457
Darin Petkov45580e42010-10-08 14:02:40 -0700458 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700459 ScopedTerminatorExitUnblocker exit_unblocker =
460 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700461 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700462 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
463 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700464 if (!PerformReplaceOperation(op, is_kernel_partition)) {
465 LOG(ERROR) << "Failed to perform replace operation "
466 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700467 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800468 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700469 }
470 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700471 if (!PerformMoveOperation(op, is_kernel_partition)) {
472 LOG(ERROR) << "Failed to perform move operation "
473 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700474 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800475 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700476 }
477 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700478 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
479 LOG(ERROR) << "Failed to perform bsdiff operation "
480 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700481 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800482 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700483 }
484 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800485
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700486 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800487 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700488 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700489 }
Don Garrette410e0f2011-11-10 15:39:01 -0800490 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700491}
492
493bool DeltaPerformer::CanPerformInstallOperation(
494 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
495 operation) {
496 // Move operations don't require any data blob, so they can always
497 // be performed
498 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
499 return true;
500
501 // See if we have the entire data blob in the buffer
502 if (operation.data_offset() < buffer_offset_) {
503 LOG(ERROR) << "we threw away data it seems?";
504 return false;
505 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700506
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700507 return (operation.data_offset() + operation.data_length()) <=
508 (buffer_offset_ + buffer_.size());
509}
510
511bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700512 const DeltaArchiveManifest_InstallOperation& operation,
513 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700514 CHECK(operation.type() == \
515 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
516 operation.type() == \
517 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
518
519 // Since we delete data off the beginning of the buffer as we use it,
520 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700521 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
522 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700523
Darin Petkov437adc42010-10-07 13:12:24 -0700524 // Extract the signature message if it's in this operation.
525 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700526
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700527 DirectExtentWriter direct_writer;
528 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
529 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700530
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700531 // Since bzip decompression is optional, we have a variable writer that will
532 // point to one of the ExtentWriter objects above.
533 ExtentWriter* writer = NULL;
534 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
535 writer = &zero_pad_writer;
536 } else if (operation.type() ==
537 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
538 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
539 writer = bzip_writer.get();
540 } else {
541 NOTREACHED();
542 }
543
544 // Create a vector of extents to pass to the ExtentWriter.
545 vector<Extent> extents;
546 for (int i = 0; i < operation.dst_extents_size(); i++) {
547 extents.push_back(operation.dst_extents(i));
548 }
549
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700550 int fd = is_kernel_partition ? kernel_fd_ : fd_;
551
552 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700553 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
554 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700555
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700556 // Update buffer
557 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700558 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700559 return true;
560}
561
562bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700563 const DeltaArchiveManifest_InstallOperation& operation,
564 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700565 // Calculate buffer size. Note, this function doesn't do a sliding
566 // window to copy in case the source and destination blocks overlap.
567 // If we wanted to do a sliding window, we could program the server
568 // to generate deltas that effectively did a sliding window.
569
570 uint64_t blocks_to_read = 0;
571 for (int i = 0; i < operation.src_extents_size(); i++)
572 blocks_to_read += operation.src_extents(i).num_blocks();
573
574 uint64_t blocks_to_write = 0;
575 for (int i = 0; i < operation.dst_extents_size(); i++)
576 blocks_to_write += operation.dst_extents(i).num_blocks();
577
578 DCHECK_EQ(blocks_to_write, blocks_to_read);
579 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700580
581 int fd = is_kernel_partition ? kernel_fd_ : fd_;
582
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700583 // Read in bytes.
584 ssize_t bytes_read = 0;
585 for (int i = 0; i < operation.src_extents_size(); i++) {
586 ssize_t bytes_read_this_iteration = 0;
587 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200588 const size_t bytes = extent.num_blocks() * block_size_;
589 if (extent.start_block() == kSparseHole) {
590 bytes_read_this_iteration = bytes;
591 memset(&buf[bytes_read], 0, bytes);
592 } else {
593 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
594 &buf[bytes_read],
595 bytes,
596 extent.start_block() * block_size_,
597 &bytes_read_this_iteration));
598 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700599 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200600 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700601 bytes_read += bytes_read_this_iteration;
602 }
603
Darin Petkov45580e42010-10-08 14:02:40 -0700604 // If this is a non-idempotent operation, request a delayed exit and clear the
605 // update state in case the operation gets interrupted. Do this as late as
606 // possible.
607 if (!IsIdempotentOperation(operation)) {
608 Terminator::set_exit_blocked(true);
609 ResetUpdateProgress(prefs_, true);
610 }
611
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700612 // Write bytes out.
613 ssize_t bytes_written = 0;
614 for (int i = 0; i < operation.dst_extents_size(); i++) {
615 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200616 const size_t bytes = extent.num_blocks() * block_size_;
617 if (extent.start_block() == kSparseHole) {
Darin Petkov741a8222013-05-02 10:02:34 +0200618 DCHECK(buf.begin() + bytes_written ==
619 std::search_n(buf.begin() + bytes_written,
620 buf.begin() + bytes_written + bytes,
621 bytes, 0));
Darin Petkov8a075a72013-04-25 14:46:09 +0200622 } else {
623 TEST_AND_RETURN_FALSE(
624 utils::PWriteAll(fd,
625 &buf[bytes_written],
626 bytes,
627 extent.start_block() * block_size_));
628 }
629 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700630 }
631 DCHECK_EQ(bytes_written, bytes_read);
632 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
633 return true;
634}
635
636bool DeltaPerformer::ExtentsToBsdiffPositionsString(
637 const RepeatedPtrField<Extent>& extents,
638 uint64_t block_size,
639 uint64_t full_length,
640 string* positions_string) {
641 string ret;
642 uint64_t length = 0;
643 for (int i = 0; i < extents.size(); i++) {
644 Extent extent = extents.Get(i);
645 int64_t start = extent.start_block();
646 uint64_t this_length = min(full_length - length,
647 extent.num_blocks() * block_size);
648 if (start == static_cast<int64_t>(kSparseHole))
649 start = -1;
650 else
651 start *= block_size;
652 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
653 length += this_length;
654 }
655 TEST_AND_RETURN_FALSE(length == full_length);
656 if (!ret.empty())
657 ret.resize(ret.size() - 1); // Strip trailing comma off
658 *positions_string = ret;
659 return true;
660}
661
662bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700663 const DeltaArchiveManifest_InstallOperation& operation,
664 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700665 // Since we delete data off the beginning of the buffer as we use it,
666 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700667 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
668 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700669
670 string input_positions;
671 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
672 block_size_,
673 operation.src_length(),
674 &input_positions));
675 string output_positions;
676 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
677 block_size_,
678 operation.dst_length(),
679 &output_positions));
680
681 string temp_filename;
682 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
683 &temp_filename,
684 NULL));
685 ScopedPathUnlinker path_unlinker(temp_filename);
686 {
687 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
688 ScopedFdCloser fd_closer(&fd);
689 TEST_AND_RETURN_FALSE(
690 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
691 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700692
Darin Petkov7f2ec752013-04-03 14:45:19 +0200693 // Update the buffer to release the patch data memory as soon as the patch
694 // file is written out.
695 buffer_offset_ += operation.data_length();
696 DiscardBufferHeadBytes(operation.data_length());
697
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700698 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Darin Petkov741a8222013-05-02 10:02:34 +0200699 const string path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700700
Darin Petkov45580e42010-10-08 14:02:40 -0700701 // If this is a non-idempotent operation, request a delayed exit and clear the
702 // update state in case the operation gets interrupted. Do this as late as
703 // possible.
704 if (!IsIdempotentOperation(operation)) {
705 Terminator::set_exit_blocked(true);
706 ResetUpdateProgress(prefs_, true);
707 }
708
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700709 vector<string> cmd;
710 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700711 cmd.push_back(path);
712 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700713 cmd.push_back(temp_filename);
714 cmd.push_back(input_positions);
715 cmd.push_back(output_positions);
716 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700717 TEST_AND_RETURN_FALSE(
718 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700719 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700720 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700721 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700722 TEST_AND_RETURN_FALSE(return_code == 0);
723
724 if (operation.dst_length() % block_size_) {
725 // Zero out rest of final block.
726 // TODO(adlr): build this into bspatch; it's more efficient that way.
727 const Extent& last_extent =
728 operation.dst_extents(operation.dst_extents_size() - 1);
729 const uint64_t end_byte =
730 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
731 const uint64_t begin_byte =
732 end_byte - (block_size_ - operation.dst_length() % block_size_);
733 vector<char> zeros(end_byte - begin_byte);
734 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700735 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700736 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700737 return true;
738}
739
Darin Petkovd7061ab2010-10-06 14:37:09 -0700740bool DeltaPerformer::ExtractSignatureMessage(
741 const DeltaArchiveManifest_InstallOperation& operation) {
742 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
743 !manifest_.has_signatures_offset() ||
744 manifest_.signatures_offset() != operation.data_offset()) {
745 return false;
746 }
747 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
748 manifest_.signatures_size() == operation.data_length());
749 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
750 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
751 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700752 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700753 buffer_.begin(),
754 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700755
756 // Save the signature blob because if the update is interrupted after the
757 // download phase we don't go through this path anymore. Some alternatives to
758 // consider:
759 //
760 // 1. On resume, re-download the signature blob from the server and re-verify
761 // it.
762 //
763 // 2. Verify the signature as soon as it's received and don't checkpoint the
764 // blob and the signed sha-256 context.
765 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
766 string(&signatures_message_data_[0],
767 signatures_message_data_.size())))
768 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700769 // The hash of all data consumed so far should be verified against the signed
770 // hash.
771 signed_hash_context_ = hash_calculator_.GetContext();
772 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
773 signed_hash_context_))
774 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700775 LOG(INFO) << "Extracted signature data of size "
776 << manifest_.signatures_size() << " at "
777 << manifest_.signatures_offset();
778 return true;
779}
780
David Zeuthena99981f2013-04-29 13:42:47 -0700781ErrorCode DeltaPerformer::ValidateMetadataSignature(
Jay Srinivasanf4318702012-09-24 11:56:24 -0700782 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700783
Jay Srinivasanf4318702012-09-24 11:56:24 -0700784 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800785 if (install_plan_->hash_checks_mandatory) {
786 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700787 return kErrorCodeDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800788 }
789
790 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700791 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
David Zeuthena99981f2013-04-29 13:42:47 -0700792 SendUmaStat(kErrorCodeDownloadMetadataSignatureMissingError);
793 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700794 }
795
796 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700797 vector<char> metadata_signature;
798 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
799 &metadata_signature)) {
800 LOG(ERROR) << "Unable to decode base64 metadata signature: "
801 << install_plan_->metadata_signature;
David Zeuthena99981f2013-04-29 13:42:47 -0700802 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700803 }
804
Jay Srinivasanf4318702012-09-24 11:56:24 -0700805 vector<char> expected_metadata_hash;
806 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700807 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700808 &expected_metadata_hash)) {
809 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
David Zeuthena99981f2013-04-29 13:42:47 -0700810 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700811 }
812
Jay Srinivasanf4318702012-09-24 11:56:24 -0700813 OmahaHashCalculator metadata_hasher;
814 metadata_hasher.Update(metadata, metadata_size);
815 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700816 LOG(ERROR) << "Unable to compute actual hash of manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700817 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700818 }
819
Jay Srinivasanf4318702012-09-24 11:56:24 -0700820 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
821 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
822 if (calculated_metadata_hash.empty()) {
823 LOG(ERROR) << "Computed actual hash of metadata is empty.";
David Zeuthena99981f2013-04-29 13:42:47 -0700824 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700825 }
826
Jay Srinivasanf4318702012-09-24 11:56:24 -0700827 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700828 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700829 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700830 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700831 utils::HexDumpVector(calculated_metadata_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700832 return kErrorCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700833 }
834
835 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700836 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700837}
838
Gilad Arnold21504f02013-05-24 08:51:22 -0700839ErrorCode DeltaPerformer::ValidateManifest() {
840 // Ensure that a full update does not contain old partition hashes, which is
841 // indicative of a delta.
842 //
843 // TODO(garnold) in general, the presence of an old partition hash should be
844 // the sole indicator for a delta update, as we would generally like update
845 // payloads to be self contained and not assume an Omaha response to tell us
846 // that. However, since this requires some massive reengineering of the update
847 // flow (making filesystem copying happen conditionally only *after*
848 // downloading and parsing of the update manifest) we'll put it off for now.
849 // See chromium-os:7597 for further discussion.
850 if (install_plan_->is_full_update &&
851 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info())) {
852 LOG(ERROR) << "Purported full payload contains old partition "
853 "hash(es), aborting update";
854 return kErrorCodePayloadMismatchedType;
855 }
856
857 // TODO(garnold) we should be adding more and more manifest checks, such as
858 // partition boundaries etc (see chromium-os:37661).
859
860 return kErrorCodeSuccess;
861}
862
David Zeuthena99981f2013-04-29 13:42:47 -0700863ErrorCode 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.
David Zeuthena99981f2013-04-29 13:42:47 -0700872 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700873 }
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;
David Zeuthena99981f2013-04-29 13:42:47 -0700892 return kErrorCodeDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800893 }
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";
David Zeuthena99981f2013-04-29 13:42:47 -0700898 SendUmaStat(kErrorCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700899 }
David Zeuthena99981f2013-04-29 13:42:47 -0700900 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700901 }
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_;
David Zeuthena99981f2013-04-29 13:42:47 -0700913 return kErrorCodeDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700914 }
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);
David Zeuthena99981f2013-04-29 13:42:47 -0700924 return kErrorCodeDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700925 }
926
David Zeuthena99981f2013-04-29 13:42:47 -0700927 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700928}
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
David Zeuthena99981f2013-04-29 13:42:47 -0700938ErrorCode 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.
David Zeuthena99981f2013-04-29 13:42:47 -0700944 TEST_AND_RETURN_VAL(kErrorCodePayloadSizeMismatchError,
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();
David Zeuthena99981f2013-04-29 13:42:47 -0700950 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700951 !payload_hash_data.empty());
David Zeuthena99981f2013-04-29 13:42:47 -0700952 TEST_AND_RETURN_VAL(kErrorCodePayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700953 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.";
David Zeuthena99981f2013-04-29 13:42:47 -0700958 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700959 }
David Zeuthena99981f2013-04-29 13:42:47 -0700960 TEST_AND_RETURN_VAL(kErrorCodeSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700961 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700962 vector<char> signed_hash_data;
David Zeuthena99981f2013-04-29 13:42:47 -0700963 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700964 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;
David Zeuthena99981f2013-04-29 13:42:47 -0700969 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700970 signed_hasher.SetContext(signed_hash_context_));
David Zeuthena99981f2013-04-29 13:42:47 -0700971 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700972 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);
David Zeuthena99981f2013-04-29 13:42:47 -0700975 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700976 !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);
David Zeuthena99981f2013-04-29 13:42:47 -0700983 return kErrorCodeDownloadPayloadPubKeyVerificationError;
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
David Zeuthena99981f2013-04-29 13:42:47 -0700993 return kErrorCodeSuccess;
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,
Chris Sosa670d6802013-03-29 14:17:45 -07001086 StringForHashBytes(install_plan_->rootfs_hash.data(),
1087 install_plan_->rootfs_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 Petkov7f2ec752013-04-03 14:45:19 +02001098 // Copy the remainder data into a temporary vector first to ensure that any
1099 // unused memory in the updated |buffer_| will be released.
1100 vector<char> temp(buffer_.begin() + count, buffer_.end());
1101 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001102}
1103
Darin Petkov0406e402010-10-06 21:33:11 -07001104bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1105 string update_check_response_hash) {
1106 int64_t next_operation = kUpdateStateOperationInvalid;
1107 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1108 &next_operation) &&
1109 next_operation != kUpdateStateOperationInvalid &&
1110 next_operation > 0);
1111
1112 string interrupted_hash;
1113 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1114 &interrupted_hash) &&
1115 !interrupted_hash.empty() &&
1116 interrupted_hash == update_check_response_hash);
1117
Darin Petkov61426142010-10-08 11:04:55 -07001118 int64_t resumed_update_failures;
1119 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1120 &resumed_update_failures) ||
1121 resumed_update_failures <= kMaxResumedUpdateFailures);
1122
Darin Petkov0406e402010-10-06 21:33:11 -07001123 // Sanity check the rest.
1124 int64_t next_data_offset = -1;
1125 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1126 &next_data_offset) &&
1127 next_data_offset >= 0);
1128
Darin Petkov437adc42010-10-07 13:12:24 -07001129 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001130 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001131 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1132 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001133
1134 int64_t manifest_metadata_size = 0;
1135 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1136 &manifest_metadata_size) &&
1137 manifest_metadata_size > 0);
1138
1139 return true;
1140}
1141
Darin Petkov9b230572010-10-08 10:20:09 -07001142bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001143 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1144 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001145 if (!quick) {
1146 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1147 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1148 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1149 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001150 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001151 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001152 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001153 }
Darin Petkov73058b42010-10-06 16:32:19 -07001154 return true;
1155}
1156
1157bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001158 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001159 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001160 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001161 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001162 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001163 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001164 hash_calculator_.GetContext()));
1165 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1166 buffer_offset_));
1167 last_updated_buffer_offset_ = buffer_offset_;
1168 }
Darin Petkov73058b42010-10-06 16:32:19 -07001169 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1170 next_operation_num_));
1171 return true;
1172}
1173
Darin Petkov9b230572010-10-08 10:20:09 -07001174bool DeltaPerformer::PrimeUpdateState() {
1175 CHECK(manifest_valid_);
1176 block_size_ = manifest_.block_size();
1177
1178 int64_t next_operation = kUpdateStateOperationInvalid;
1179 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1180 next_operation == kUpdateStateOperationInvalid ||
1181 next_operation <= 0) {
1182 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001183 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001184 return true;
1185 }
1186 next_operation_num_ = next_operation;
1187
1188 // Resuming an update -- load the rest of the update state.
1189 int64_t next_data_offset = -1;
1190 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1191 &next_data_offset) &&
1192 next_data_offset >= 0);
1193 buffer_offset_ = next_data_offset;
1194
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001195 // The signed hash context and the signature blob may be empty if the
1196 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001197 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1198 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001199 string signature_blob;
1200 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1201 signatures_message_data_.assign(signature_blob.begin(),
1202 signature_blob.end());
1203 }
Darin Petkov9b230572010-10-08 10:20:09 -07001204
1205 string hash_context;
1206 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1207 &hash_context) &&
1208 hash_calculator_.SetContext(hash_context));
1209
1210 int64_t manifest_metadata_size = 0;
1211 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1212 &manifest_metadata_size) &&
1213 manifest_metadata_size > 0);
1214 manifest_metadata_size_ = manifest_metadata_size;
1215
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001216 // Advance the download progress to reflect what doesn't need to be
1217 // re-downloaded.
1218 total_bytes_received_ += buffer_offset_;
1219
Darin Petkov61426142010-10-08 11:04:55 -07001220 // Speculatively count the resume as a failure.
1221 int64_t resumed_update_failures;
1222 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1223 resumed_update_failures++;
1224 } else {
1225 resumed_update_failures = 1;
1226 }
1227 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001228 return true;
1229}
1230
David Zeuthena99981f2013-04-29 13:42:47 -07001231void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001232 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001233}
1234
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001235} // namespace chromeos_update_engine