blob: 68161d27ef9fea58ea621dfb2f8922254def0b28 [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);
Gilad Arnold5cac5912013-05-24 17:21:17 -0700380 if (result == kMetadataParseError)
Don Garrette410e0f2011-11-10 15:39:01 -0800381 return false;
Gilad Arnold5cac5912013-05-24 17:21:17 -0700382 if (result == kMetadataParseInsufficientData)
Don Garrette410e0f2011-11-10 15:39:01 -0800383 return true;
Gilad Arnold21504f02013-05-24 08:51:22 -0700384
385 // Checks the integrity of the payload manifest.
386 if ((*error = ValidateManifest()) != kErrorCodeSuccess)
387 return false;
388
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700389 // Remove protobuf and header info from buffer_, so buffer_ contains
390 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700391 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700392 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700393 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700394 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700395 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700396
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700397 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700398 if (!PrimeUpdateState()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700399 *error = kErrorCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700400 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800401 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700402 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800403
404 num_rootfs_operations_ = manifest_.install_operations_size();
405 num_total_operations_ =
406 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
407 if (next_operation_num_ > 0)
408 UpdateOverallProgress(true, "Resuming after ");
409 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700410 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800411
412 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700413 // Check if we should cancel the current attempt for any reason.
414 // In this case, *error will have already been populated with the reason
415 // why we're cancelling.
416 if (system_state_->update_attempter()->ShouldCancel(error))
417 return false;
418
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800419 const bool is_kernel_partition =
420 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700421 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800422 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700423 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800424 next_operation_num_ - num_rootfs_operations_) :
425 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700426 if (!CanPerformInstallOperation(op)) {
427 // This means we don't have enough bytes received yet to carry out the
428 // next operation.
429 return true;
430 }
431
Jay Srinivasanf4318702012-09-24 11:56:24 -0700432 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700433 // Otherwise, keep the old behavior. This serves as a knob to disable
434 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800435 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
436 // we would have already failed in ParsePayloadMetadata method and thus not
437 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700438 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700439 // Note: Validate must be called only if CanPerformInstallOperation is
440 // called. Otherwise, we might be failing operations before even if there
441 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800442 *error = ValidateOperationHash(op);
David Zeuthena99981f2013-04-29 13:42:47 -0700443 if (*error != kErrorCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800444 if (install_plan_->hash_checks_mandatory) {
445 LOG(ERROR) << "Mandatory operation hash check failed";
446 return false;
447 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700448
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800449 // For non-mandatory cases, just send a UMA stat.
450 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700451 SendUmaStat(*error);
David Zeuthena99981f2013-04-29 13:42:47 -0700452 *error = kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700453 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700454 }
455
Darin Petkov45580e42010-10-08 14:02:40 -0700456 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700457 ScopedTerminatorExitUnblocker exit_unblocker =
458 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700459 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700460 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
461 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700462 if (!PerformReplaceOperation(op, is_kernel_partition)) {
463 LOG(ERROR) << "Failed to perform replace operation "
464 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700465 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800466 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700467 }
468 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700469 if (!PerformMoveOperation(op, is_kernel_partition)) {
470 LOG(ERROR) << "Failed to perform move operation "
471 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700472 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800473 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700474 }
475 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700476 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
477 LOG(ERROR) << "Failed to perform bsdiff operation "
478 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700479 *error = kErrorCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800480 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700481 }
482 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800483
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700484 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800485 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700486 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700487 }
Don Garrette410e0f2011-11-10 15:39:01 -0800488 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700489}
490
David Zeuthen8f191b22013-08-06 12:27:50 -0700491bool DeltaPerformer::IsManifestValid() {
492 return manifest_valid_;
493}
494
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700495bool DeltaPerformer::CanPerformInstallOperation(
496 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
497 operation) {
498 // Move operations don't require any data blob, so they can always
499 // be performed
500 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
501 return true;
502
503 // See if we have the entire data blob in the buffer
504 if (operation.data_offset() < buffer_offset_) {
505 LOG(ERROR) << "we threw away data it seems?";
506 return false;
507 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700508
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700509 return (operation.data_offset() + operation.data_length()) <=
510 (buffer_offset_ + buffer_.size());
511}
512
513bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700514 const DeltaArchiveManifest_InstallOperation& operation,
515 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700516 CHECK(operation.type() == \
517 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
518 operation.type() == \
519 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
520
521 // Since we delete data off the beginning of the buffer as we use it,
522 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700523 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
524 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700525
Darin Petkov437adc42010-10-07 13:12:24 -0700526 // Extract the signature message if it's in this operation.
527 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700528
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700529 DirectExtentWriter direct_writer;
530 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
531 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700532
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700533 // Since bzip decompression is optional, we have a variable writer that will
534 // point to one of the ExtentWriter objects above.
535 ExtentWriter* writer = NULL;
536 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
537 writer = &zero_pad_writer;
538 } else if (operation.type() ==
539 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
540 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
541 writer = bzip_writer.get();
542 } else {
543 NOTREACHED();
544 }
545
546 // Create a vector of extents to pass to the ExtentWriter.
547 vector<Extent> extents;
548 for (int i = 0; i < operation.dst_extents_size(); i++) {
549 extents.push_back(operation.dst_extents(i));
550 }
551
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700552 int fd = is_kernel_partition ? kernel_fd_ : fd_;
553
554 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700555 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
556 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700557
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700558 // Update buffer
559 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700560 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700561 return true;
562}
563
564bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700565 const DeltaArchiveManifest_InstallOperation& operation,
566 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700567 // Calculate buffer size. Note, this function doesn't do a sliding
568 // window to copy in case the source and destination blocks overlap.
569 // If we wanted to do a sliding window, we could program the server
570 // to generate deltas that effectively did a sliding window.
571
572 uint64_t blocks_to_read = 0;
573 for (int i = 0; i < operation.src_extents_size(); i++)
574 blocks_to_read += operation.src_extents(i).num_blocks();
575
576 uint64_t blocks_to_write = 0;
577 for (int i = 0; i < operation.dst_extents_size(); i++)
578 blocks_to_write += operation.dst_extents(i).num_blocks();
579
580 DCHECK_EQ(blocks_to_write, blocks_to_read);
581 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700582
583 int fd = is_kernel_partition ? kernel_fd_ : fd_;
584
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700585 // Read in bytes.
586 ssize_t bytes_read = 0;
587 for (int i = 0; i < operation.src_extents_size(); i++) {
588 ssize_t bytes_read_this_iteration = 0;
589 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200590 const size_t bytes = extent.num_blocks() * block_size_;
591 if (extent.start_block() == kSparseHole) {
592 bytes_read_this_iteration = bytes;
593 memset(&buf[bytes_read], 0, bytes);
594 } else {
595 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
596 &buf[bytes_read],
597 bytes,
598 extent.start_block() * block_size_,
599 &bytes_read_this_iteration));
600 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700601 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200602 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700603 bytes_read += bytes_read_this_iteration;
604 }
605
Darin Petkov45580e42010-10-08 14:02:40 -0700606 // If this is a non-idempotent operation, request a delayed exit and clear the
607 // update state in case the operation gets interrupted. Do this as late as
608 // possible.
609 if (!IsIdempotentOperation(operation)) {
610 Terminator::set_exit_blocked(true);
611 ResetUpdateProgress(prefs_, true);
612 }
613
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700614 // Write bytes out.
615 ssize_t bytes_written = 0;
616 for (int i = 0; i < operation.dst_extents_size(); i++) {
617 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200618 const size_t bytes = extent.num_blocks() * block_size_;
619 if (extent.start_block() == kSparseHole) {
Darin Petkov741a8222013-05-02 10:02:34 +0200620 DCHECK(buf.begin() + bytes_written ==
621 std::search_n(buf.begin() + bytes_written,
622 buf.begin() + bytes_written + bytes,
623 bytes, 0));
Darin Petkov8a075a72013-04-25 14:46:09 +0200624 } else {
625 TEST_AND_RETURN_FALSE(
626 utils::PWriteAll(fd,
627 &buf[bytes_written],
628 bytes,
629 extent.start_block() * block_size_));
630 }
631 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700632 }
633 DCHECK_EQ(bytes_written, bytes_read);
634 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
635 return true;
636}
637
638bool DeltaPerformer::ExtentsToBsdiffPositionsString(
639 const RepeatedPtrField<Extent>& extents,
640 uint64_t block_size,
641 uint64_t full_length,
642 string* positions_string) {
643 string ret;
644 uint64_t length = 0;
645 for (int i = 0; i < extents.size(); i++) {
646 Extent extent = extents.Get(i);
647 int64_t start = extent.start_block();
648 uint64_t this_length = min(full_length - length,
649 extent.num_blocks() * block_size);
650 if (start == static_cast<int64_t>(kSparseHole))
651 start = -1;
652 else
653 start *= block_size;
654 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
655 length += this_length;
656 }
657 TEST_AND_RETURN_FALSE(length == full_length);
658 if (!ret.empty())
659 ret.resize(ret.size() - 1); // Strip trailing comma off
660 *positions_string = ret;
661 return true;
662}
663
664bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700665 const DeltaArchiveManifest_InstallOperation& operation,
666 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700667 // Since we delete data off the beginning of the buffer as we use it,
668 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700669 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
670 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700671
672 string input_positions;
673 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
674 block_size_,
675 operation.src_length(),
676 &input_positions));
677 string output_positions;
678 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
679 block_size_,
680 operation.dst_length(),
681 &output_positions));
682
683 string temp_filename;
684 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
685 &temp_filename,
686 NULL));
687 ScopedPathUnlinker path_unlinker(temp_filename);
688 {
689 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
690 ScopedFdCloser fd_closer(&fd);
691 TEST_AND_RETURN_FALSE(
692 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
693 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700694
Darin Petkov7f2ec752013-04-03 14:45:19 +0200695 // Update the buffer to release the patch data memory as soon as the patch
696 // file is written out.
697 buffer_offset_ += operation.data_length();
698 DiscardBufferHeadBytes(operation.data_length());
699
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700700 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Darin Petkov3d1670d2013-07-12 14:37:06 +0200701 const string path = StringPrintf("/proc/self/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700702
Darin Petkov45580e42010-10-08 14:02:40 -0700703 // If this is a non-idempotent operation, request a delayed exit and clear the
704 // update state in case the operation gets interrupted. Do this as late as
705 // possible.
706 if (!IsIdempotentOperation(operation)) {
707 Terminator::set_exit_blocked(true);
708 ResetUpdateProgress(prefs_, true);
709 }
710
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700711 vector<string> cmd;
712 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700713 cmd.push_back(path);
714 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700715 cmd.push_back(temp_filename);
716 cmd.push_back(input_positions);
717 cmd.push_back(output_positions);
718 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700719 TEST_AND_RETURN_FALSE(
720 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700721 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700722 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700723 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700724 TEST_AND_RETURN_FALSE(return_code == 0);
725
726 if (operation.dst_length() % block_size_) {
727 // Zero out rest of final block.
728 // TODO(adlr): build this into bspatch; it's more efficient that way.
729 const Extent& last_extent =
730 operation.dst_extents(operation.dst_extents_size() - 1);
731 const uint64_t end_byte =
732 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
733 const uint64_t begin_byte =
734 end_byte - (block_size_ - operation.dst_length() % block_size_);
735 vector<char> zeros(end_byte - begin_byte);
736 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700737 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700738 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700739 return true;
740}
741
Darin Petkovd7061ab2010-10-06 14:37:09 -0700742bool DeltaPerformer::ExtractSignatureMessage(
743 const DeltaArchiveManifest_InstallOperation& operation) {
744 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
745 !manifest_.has_signatures_offset() ||
746 manifest_.signatures_offset() != operation.data_offset()) {
747 return false;
748 }
749 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
750 manifest_.signatures_size() == operation.data_length());
751 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
752 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
753 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700754 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700755 buffer_.begin(),
756 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700757
758 // Save the signature blob because if the update is interrupted after the
759 // download phase we don't go through this path anymore. Some alternatives to
760 // consider:
761 //
762 // 1. On resume, re-download the signature blob from the server and re-verify
763 // it.
764 //
765 // 2. Verify the signature as soon as it's received and don't checkpoint the
766 // blob and the signed sha-256 context.
767 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
768 string(&signatures_message_data_[0],
769 signatures_message_data_.size())))
770 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700771 // The hash of all data consumed so far should be verified against the signed
772 // hash.
773 signed_hash_context_ = hash_calculator_.GetContext();
774 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
775 signed_hash_context_))
776 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700777 LOG(INFO) << "Extracted signature data of size "
778 << manifest_.signatures_size() << " at "
779 << manifest_.signatures_offset();
780 return true;
781}
782
David Zeuthena99981f2013-04-29 13:42:47 -0700783ErrorCode DeltaPerformer::ValidateMetadataSignature(
Jay Srinivasanf4318702012-09-24 11:56:24 -0700784 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700785
Jay Srinivasanf4318702012-09-24 11:56:24 -0700786 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800787 if (install_plan_->hash_checks_mandatory) {
788 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700789 return kErrorCodeDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800790 }
791
792 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700793 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
David Zeuthena99981f2013-04-29 13:42:47 -0700794 SendUmaStat(kErrorCodeDownloadMetadataSignatureMissingError);
795 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700796 }
797
798 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700799 vector<char> metadata_signature;
800 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
801 &metadata_signature)) {
802 LOG(ERROR) << "Unable to decode base64 metadata signature: "
803 << install_plan_->metadata_signature;
David Zeuthena99981f2013-04-29 13:42:47 -0700804 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700805 }
806
Jay Srinivasanf4318702012-09-24 11:56:24 -0700807 vector<char> expected_metadata_hash;
808 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700809 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700810 &expected_metadata_hash)) {
811 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
David Zeuthena99981f2013-04-29 13:42:47 -0700812 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700813 }
814
Jay Srinivasanf4318702012-09-24 11:56:24 -0700815 OmahaHashCalculator metadata_hasher;
816 metadata_hasher.Update(metadata, metadata_size);
817 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700818 LOG(ERROR) << "Unable to compute actual hash of manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700819 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700820 }
821
Jay Srinivasanf4318702012-09-24 11:56:24 -0700822 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
823 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
824 if (calculated_metadata_hash.empty()) {
825 LOG(ERROR) << "Computed actual hash of metadata is empty.";
David Zeuthena99981f2013-04-29 13:42:47 -0700826 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700827 }
828
Jay Srinivasanf4318702012-09-24 11:56:24 -0700829 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700830 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700831 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700832 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700833 utils::HexDumpVector(calculated_metadata_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700834 return kErrorCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700835 }
836
837 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700838 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700839}
840
Gilad Arnold21504f02013-05-24 08:51:22 -0700841ErrorCode DeltaPerformer::ValidateManifest() {
842 // Ensure that a full update does not contain old partition hashes, which is
843 // indicative of a delta.
844 //
845 // TODO(garnold) in general, the presence of an old partition hash should be
846 // the sole indicator for a delta update, as we would generally like update
847 // payloads to be self contained and not assume an Omaha response to tell us
848 // that. However, since this requires some massive reengineering of the update
849 // flow (making filesystem copying happen conditionally only *after*
850 // downloading and parsing of the update manifest) we'll put it off for now.
851 // See chromium-os:7597 for further discussion.
852 if (install_plan_->is_full_update &&
853 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info())) {
854 LOG(ERROR) << "Purported full payload contains old partition "
855 "hash(es), aborting update";
856 return kErrorCodePayloadMismatchedType;
857 }
858
859 // TODO(garnold) we should be adding more and more manifest checks, such as
860 // partition boundaries etc (see chromium-os:37661).
861
862 return kErrorCodeSuccess;
863}
864
David Zeuthena99981f2013-04-29 13:42:47 -0700865ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800866 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700867
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700868 if (!operation.data_sha256_hash().size()) {
869 if (!operation.data_length()) {
870 // Operations that do not have any data blob won't have any operation hash
871 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700872 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800873 // has already been validated. This is true for both HTTP and HTTPS cases.
David Zeuthena99981f2013-04-29 13:42:47 -0700874 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700875 }
876
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800877 // No hash is present for an operation that has data blobs. This shouldn't
878 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700879 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800880 // hashes. So if it happens it means either we've turned operation hash
881 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700882 // One caveat though: The last operation is a dummy signature operation
883 // that doesn't have a hash at the time the manifest is created. So we
884 // should not complaint about that operation. This operation can be
885 // recognized by the fact that it's offset is mentioned in the manifest.
886 if (manifest_.signatures_offset() &&
887 manifest_.signatures_offset() == operation.data_offset()) {
888 LOG(INFO) << "Skipping hash verification for signature operation "
889 << next_operation_num_ + 1;
890 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800891 if (install_plan_->hash_checks_mandatory) {
892 LOG(ERROR) << "Missing mandatory operation hash for operation "
893 << next_operation_num_ + 1;
David Zeuthena99981f2013-04-29 13:42:47 -0700894 return kErrorCodeDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800895 }
896
897 // For non-mandatory cases, just send a UMA stat.
898 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
899 << " as there's no operation hash in manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700900 SendUmaStat(kErrorCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700901 }
David Zeuthena99981f2013-04-29 13:42:47 -0700902 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700903 }
904
905 vector<char> expected_op_hash;
906 expected_op_hash.assign(operation.data_sha256_hash().data(),
907 (operation.data_sha256_hash().data() +
908 operation.data_sha256_hash().size()));
909
910 OmahaHashCalculator operation_hasher;
911 operation_hasher.Update(&buffer_[0], operation.data_length());
912 if (!operation_hasher.Finalize()) {
913 LOG(ERROR) << "Unable to compute actual hash of operation "
914 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700915 return kErrorCodeDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700916 }
917
918 vector<char> calculated_op_hash = operation_hasher.raw_hash();
919 if (calculated_op_hash != expected_op_hash) {
920 LOG(ERROR) << "Hash verification failed for operation "
921 << next_operation_num_ << ". Expected hash = ";
922 utils::HexDumpVector(expected_op_hash);
923 LOG(ERROR) << "Calculated hash over " << operation.data_length()
924 << " bytes at offset: " << operation.data_offset() << " = ";
925 utils::HexDumpVector(calculated_op_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700926 return kErrorCodeDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700927 }
928
David Zeuthena99981f2013-04-29 13:42:47 -0700929 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700930}
931
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700932#define TEST_AND_RETURN_VAL(_retval, _condition) \
933 do { \
934 if (!(_condition)) { \
935 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
936 return _retval; \
937 } \
938 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700939
David Zeuthena99981f2013-04-29 13:42:47 -0700940ErrorCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700941 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700942 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700943 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700944
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700945 // Verifies the download size.
David Zeuthena99981f2013-04-29 13:42:47 -0700946 TEST_AND_RETURN_VAL(kErrorCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700947 update_check_response_size ==
948 manifest_metadata_size_ + buffer_offset_);
949
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700950 // Verifies the payload hash.
951 const string& payload_hash_data = hash_calculator_.hash();
David Zeuthena99981f2013-04-29 13:42:47 -0700952 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700953 !payload_hash_data.empty());
David Zeuthena99981f2013-04-29 13:42:47 -0700954 TEST_AND_RETURN_VAL(kErrorCodePayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700955 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700956
Darin Petkov437adc42010-10-07 13:12:24 -0700957 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700958 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700959 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
David Zeuthena99981f2013-04-29 13:42:47 -0700960 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700961 }
David Zeuthena99981f2013-04-29 13:42:47 -0700962 TEST_AND_RETURN_VAL(kErrorCodeSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700963 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700964 vector<char> signed_hash_data;
David Zeuthena99981f2013-04-29 13:42:47 -0700965 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700966 PayloadSigner::VerifySignature(
967 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700968 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700969 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700970 OmahaHashCalculator signed_hasher;
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.SetContext(signed_hash_context_));
David Zeuthena99981f2013-04-29 13:42:47 -0700973 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700974 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700975 vector<char> hash_data = signed_hasher.raw_hash();
976 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -0700977 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700978 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700979 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700980 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700981 "Attached Signature:";
982 utils::HexDumpVector(signed_hash_data);
983 LOG(ERROR) << "Computed Signature:";
984 utils::HexDumpVector(hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -0700985 return kErrorCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700986 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800987
988 // At this point, we are guaranteed to have downloaded a full payload, i.e
989 // the one whose size matches the size mentioned in Omaha response. If any
990 // errors happen after this, it's likely a problem with the payload itself or
991 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800992 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800993 system_state_->payload_state()->DownloadComplete();
994
David Zeuthena99981f2013-04-29 13:42:47 -0700995 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700996}
997
Darin Petkov3aefa862010-12-07 14:45:00 -0800998bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
999 vector<char>* kernel_hash,
1000 uint64_t* rootfs_size,
1001 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001002 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1003 manifest_.has_new_kernel_info() &&
1004 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001005 *kernel_size = manifest_.new_kernel_info().size();
1006 *rootfs_size = manifest_.new_rootfs_info().size();
1007 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1008 manifest_.new_kernel_info().hash().end());
1009 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1010 manifest_.new_rootfs_info().hash().end());
1011 kernel_hash->swap(new_kernel_hash);
1012 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001013 return true;
1014}
1015
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001016namespace {
1017void LogVerifyError(bool is_kern,
1018 const string& local_hash,
1019 const string& expected_hash) {
1020 const char* type = is_kern ? "kernel" : "rootfs";
1021 LOG(ERROR) << "This is a server-side error due to "
1022 << "mismatched delta update image!";
1023 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1024 << "update that must be applied over a " << type << " with "
1025 << "a specific checksum, but the " << type << " we're starting "
1026 << "with doesn't have that checksum! This means that "
1027 << "the delta I've been given doesn't match my existing "
1028 << "system. The " << type << " partition I have has hash: "
1029 << local_hash << " but the update expected me to have "
1030 << expected_hash << " .";
1031 if (is_kern) {
1032 LOG(INFO) << "To get the checksum of a kernel partition on a "
1033 << "booted machine, run this command (change /dev/sda2 "
1034 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1035 << "openssl dgst -sha256 -binary | openssl base64";
1036 } else {
1037 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1038 << "booted machine, run this command (change /dev/sda3 "
1039 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1040 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1041 << "| sed 's/[^0-9]*//') / 256 )) | "
1042 << "openssl dgst -sha256 -binary | openssl base64";
1043 }
1044 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1045 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1046}
1047
1048string StringForHashBytes(const void* bytes, size_t size) {
1049 string ret;
1050 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1051 ret = "<unknown>";
1052 }
1053 return ret;
1054}
1055} // namespace
1056
Darin Petkov698d0412010-10-13 10:59:44 -07001057bool DeltaPerformer::VerifySourcePartitions() {
1058 LOG(INFO) << "Verifying source partitions.";
1059 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001060 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001061 if (manifest_.has_old_kernel_info()) {
1062 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001063 bool valid =
1064 !install_plan_->kernel_hash.empty() &&
1065 install_plan_->kernel_hash.size() == info.hash().size() &&
1066 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001067 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001068 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001069 if (!valid) {
1070 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001071 StringForHashBytes(install_plan_->kernel_hash.data(),
1072 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001073 StringForHashBytes(info.hash().data(),
1074 info.hash().size()));
1075 }
1076 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001077 }
1078 if (manifest_.has_old_rootfs_info()) {
1079 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001080 bool valid =
1081 !install_plan_->rootfs_hash.empty() &&
1082 install_plan_->rootfs_hash.size() == info.hash().size() &&
1083 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001084 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001085 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001086 if (!valid) {
1087 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001088 StringForHashBytes(install_plan_->rootfs_hash.data(),
1089 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001090 StringForHashBytes(info.hash().data(),
1091 info.hash().size()));
1092 }
1093 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001094 }
1095 return true;
1096}
1097
Darin Petkov437adc42010-10-07 13:12:24 -07001098void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1099 hash_calculator_.Update(&buffer_[0], count);
Darin Petkov7f2ec752013-04-03 14:45:19 +02001100 // Copy the remainder data into a temporary vector first to ensure that any
1101 // unused memory in the updated |buffer_| will be released.
1102 vector<char> temp(buffer_.begin() + count, buffer_.end());
1103 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001104}
1105
Darin Petkov0406e402010-10-06 21:33:11 -07001106bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1107 string update_check_response_hash) {
1108 int64_t next_operation = kUpdateStateOperationInvalid;
1109 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1110 &next_operation) &&
1111 next_operation != kUpdateStateOperationInvalid &&
1112 next_operation > 0);
1113
1114 string interrupted_hash;
1115 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1116 &interrupted_hash) &&
David Zeuthenc41c2282013-06-17 16:33:06 -07001117 !interrupted_hash.empty() &&
1118 interrupted_hash == update_check_response_hash);
Darin Petkov0406e402010-10-06 21:33:11 -07001119
Darin Petkov61426142010-10-08 11:04:55 -07001120 int64_t resumed_update_failures;
1121 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1122 &resumed_update_failures) ||
1123 resumed_update_failures <= kMaxResumedUpdateFailures);
1124
Darin Petkov0406e402010-10-06 21:33:11 -07001125 // Sanity check the rest.
1126 int64_t next_data_offset = -1;
1127 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1128 &next_data_offset) &&
1129 next_data_offset >= 0);
1130
Darin Petkov437adc42010-10-07 13:12:24 -07001131 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001132 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001133 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1134 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001135
1136 int64_t manifest_metadata_size = 0;
1137 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1138 &manifest_metadata_size) &&
1139 manifest_metadata_size > 0);
1140
1141 return true;
1142}
1143
Darin Petkov9b230572010-10-08 10:20:09 -07001144bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001145 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1146 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001147 if (!quick) {
1148 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1149 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1150 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1151 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001152 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001153 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001154 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001155 }
Darin Petkov73058b42010-10-06 16:32:19 -07001156 return true;
1157}
1158
1159bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001160 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001161 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001162 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001163 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001164 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001165 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001166 hash_calculator_.GetContext()));
1167 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1168 buffer_offset_));
1169 last_updated_buffer_offset_ = buffer_offset_;
1170 }
Darin Petkov73058b42010-10-06 16:32:19 -07001171 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1172 next_operation_num_));
1173 return true;
1174}
1175
Darin Petkov9b230572010-10-08 10:20:09 -07001176bool DeltaPerformer::PrimeUpdateState() {
1177 CHECK(manifest_valid_);
1178 block_size_ = manifest_.block_size();
1179
1180 int64_t next_operation = kUpdateStateOperationInvalid;
1181 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1182 next_operation == kUpdateStateOperationInvalid ||
1183 next_operation <= 0) {
1184 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001185 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001186 return true;
1187 }
1188 next_operation_num_ = next_operation;
1189
1190 // Resuming an update -- load the rest of the update state.
1191 int64_t next_data_offset = -1;
1192 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1193 &next_data_offset) &&
1194 next_data_offset >= 0);
1195 buffer_offset_ = next_data_offset;
1196
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001197 // The signed hash context and the signature blob may be empty if the
1198 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001199 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1200 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001201 string signature_blob;
1202 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1203 signatures_message_data_.assign(signature_blob.begin(),
1204 signature_blob.end());
1205 }
Darin Petkov9b230572010-10-08 10:20:09 -07001206
1207 string hash_context;
1208 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1209 &hash_context) &&
1210 hash_calculator_.SetContext(hash_context));
1211
1212 int64_t manifest_metadata_size = 0;
1213 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1214 &manifest_metadata_size) &&
1215 manifest_metadata_size > 0);
1216 manifest_metadata_size_ = manifest_metadata_size;
1217
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001218 // Advance the download progress to reflect what doesn't need to be
1219 // re-downloaded.
1220 total_bytes_received_ += buffer_offset_;
1221
Darin Petkov61426142010-10-08 11:04:55 -07001222 // Speculatively count the resume as a failure.
1223 int64_t resumed_update_failures;
1224 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1225 resumed_update_failures++;
1226 } else {
1227 resumed_update_failures = 1;
1228 }
1229 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001230 return true;
1231}
1232
David Zeuthena99981f2013-04-29 13:42:47 -07001233void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001234 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001235}
1236
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001237} // namespace chromeos_update_engine