blob: dd9a4c727f62b71274cf46bab7933278f3257b25 [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
491bool DeltaPerformer::CanPerformInstallOperation(
492 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
493 operation) {
494 // Move operations don't require any data blob, so they can always
495 // be performed
496 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
497 return true;
498
499 // See if we have the entire data blob in the buffer
500 if (operation.data_offset() < buffer_offset_) {
501 LOG(ERROR) << "we threw away data it seems?";
502 return false;
503 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700504
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700505 return (operation.data_offset() + operation.data_length()) <=
506 (buffer_offset_ + buffer_.size());
507}
508
509bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700510 const DeltaArchiveManifest_InstallOperation& operation,
511 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700512 CHECK(operation.type() == \
513 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
514 operation.type() == \
515 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
516
517 // Since we delete data off the beginning of the buffer as we use it,
518 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700519 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
520 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700521
Darin Petkov437adc42010-10-07 13:12:24 -0700522 // Extract the signature message if it's in this operation.
523 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700524
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700525 DirectExtentWriter direct_writer;
526 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
527 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700528
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700529 // Since bzip decompression is optional, we have a variable writer that will
530 // point to one of the ExtentWriter objects above.
531 ExtentWriter* writer = NULL;
532 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
533 writer = &zero_pad_writer;
534 } else if (operation.type() ==
535 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
536 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
537 writer = bzip_writer.get();
538 } else {
539 NOTREACHED();
540 }
541
542 // Create a vector of extents to pass to the ExtentWriter.
543 vector<Extent> extents;
544 for (int i = 0; i < operation.dst_extents_size(); i++) {
545 extents.push_back(operation.dst_extents(i));
546 }
547
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700548 int fd = is_kernel_partition ? kernel_fd_ : fd_;
549
550 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700551 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
552 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700553
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700554 // Update buffer
555 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700556 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700557 return true;
558}
559
560bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700561 const DeltaArchiveManifest_InstallOperation& operation,
562 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700563 // Calculate buffer size. Note, this function doesn't do a sliding
564 // window to copy in case the source and destination blocks overlap.
565 // If we wanted to do a sliding window, we could program the server
566 // to generate deltas that effectively did a sliding window.
567
568 uint64_t blocks_to_read = 0;
569 for (int i = 0; i < operation.src_extents_size(); i++)
570 blocks_to_read += operation.src_extents(i).num_blocks();
571
572 uint64_t blocks_to_write = 0;
573 for (int i = 0; i < operation.dst_extents_size(); i++)
574 blocks_to_write += operation.dst_extents(i).num_blocks();
575
576 DCHECK_EQ(blocks_to_write, blocks_to_read);
577 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700578
579 int fd = is_kernel_partition ? kernel_fd_ : fd_;
580
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700581 // Read in bytes.
582 ssize_t bytes_read = 0;
583 for (int i = 0; i < operation.src_extents_size(); i++) {
584 ssize_t bytes_read_this_iteration = 0;
585 const Extent& extent = operation.src_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200586 const size_t bytes = extent.num_blocks() * block_size_;
587 if (extent.start_block() == kSparseHole) {
588 bytes_read_this_iteration = bytes;
589 memset(&buf[bytes_read], 0, bytes);
590 } else {
591 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
592 &buf[bytes_read],
593 bytes,
594 extent.start_block() * block_size_,
595 &bytes_read_this_iteration));
596 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700597 TEST_AND_RETURN_FALSE(
Darin Petkov8a075a72013-04-25 14:46:09 +0200598 bytes_read_this_iteration == static_cast<ssize_t>(bytes));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700599 bytes_read += bytes_read_this_iteration;
600 }
601
Darin Petkov45580e42010-10-08 14:02:40 -0700602 // If this is a non-idempotent operation, request a delayed exit and clear the
603 // update state in case the operation gets interrupted. Do this as late as
604 // possible.
605 if (!IsIdempotentOperation(operation)) {
606 Terminator::set_exit_blocked(true);
607 ResetUpdateProgress(prefs_, true);
608 }
609
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700610 // Write bytes out.
611 ssize_t bytes_written = 0;
612 for (int i = 0; i < operation.dst_extents_size(); i++) {
613 const Extent& extent = operation.dst_extents(i);
Darin Petkov8a075a72013-04-25 14:46:09 +0200614 const size_t bytes = extent.num_blocks() * block_size_;
615 if (extent.start_block() == kSparseHole) {
Darin Petkov741a8222013-05-02 10:02:34 +0200616 DCHECK(buf.begin() + bytes_written ==
617 std::search_n(buf.begin() + bytes_written,
618 buf.begin() + bytes_written + bytes,
619 bytes, 0));
Darin Petkov8a075a72013-04-25 14:46:09 +0200620 } else {
621 TEST_AND_RETURN_FALSE(
622 utils::PWriteAll(fd,
623 &buf[bytes_written],
624 bytes,
625 extent.start_block() * block_size_));
626 }
627 bytes_written += bytes;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700628 }
629 DCHECK_EQ(bytes_written, bytes_read);
630 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
631 return true;
632}
633
634bool DeltaPerformer::ExtentsToBsdiffPositionsString(
635 const RepeatedPtrField<Extent>& extents,
636 uint64_t block_size,
637 uint64_t full_length,
638 string* positions_string) {
639 string ret;
640 uint64_t length = 0;
641 for (int i = 0; i < extents.size(); i++) {
642 Extent extent = extents.Get(i);
643 int64_t start = extent.start_block();
644 uint64_t this_length = min(full_length - length,
645 extent.num_blocks() * block_size);
646 if (start == static_cast<int64_t>(kSparseHole))
647 start = -1;
648 else
649 start *= block_size;
650 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
651 length += this_length;
652 }
653 TEST_AND_RETURN_FALSE(length == full_length);
654 if (!ret.empty())
655 ret.resize(ret.size() - 1); // Strip trailing comma off
656 *positions_string = ret;
657 return true;
658}
659
660bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700661 const DeltaArchiveManifest_InstallOperation& operation,
662 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700663 // Since we delete data off the beginning of the buffer as we use it,
664 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700665 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
666 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700667
668 string input_positions;
669 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
670 block_size_,
671 operation.src_length(),
672 &input_positions));
673 string output_positions;
674 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
675 block_size_,
676 operation.dst_length(),
677 &output_positions));
678
679 string temp_filename;
680 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
681 &temp_filename,
682 NULL));
683 ScopedPathUnlinker path_unlinker(temp_filename);
684 {
685 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
686 ScopedFdCloser fd_closer(&fd);
687 TEST_AND_RETURN_FALSE(
688 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
689 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700690
Darin Petkov7f2ec752013-04-03 14:45:19 +0200691 // Update the buffer to release the patch data memory as soon as the patch
692 // file is written out.
693 buffer_offset_ += operation.data_length();
694 DiscardBufferHeadBytes(operation.data_length());
695
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700696 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Darin Petkov741a8222013-05-02 10:02:34 +0200697 const string path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700698
Darin Petkov45580e42010-10-08 14:02:40 -0700699 // If this is a non-idempotent operation, request a delayed exit and clear the
700 // update state in case the operation gets interrupted. Do this as late as
701 // possible.
702 if (!IsIdempotentOperation(operation)) {
703 Terminator::set_exit_blocked(true);
704 ResetUpdateProgress(prefs_, true);
705 }
706
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700707 vector<string> cmd;
708 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700709 cmd.push_back(path);
710 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700711 cmd.push_back(temp_filename);
712 cmd.push_back(input_positions);
713 cmd.push_back(output_positions);
714 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700715 TEST_AND_RETURN_FALSE(
716 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700717 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700718 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700719 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700720 TEST_AND_RETURN_FALSE(return_code == 0);
721
722 if (operation.dst_length() % block_size_) {
723 // Zero out rest of final block.
724 // TODO(adlr): build this into bspatch; it's more efficient that way.
725 const Extent& last_extent =
726 operation.dst_extents(operation.dst_extents_size() - 1);
727 const uint64_t end_byte =
728 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
729 const uint64_t begin_byte =
730 end_byte - (block_size_ - operation.dst_length() % block_size_);
731 vector<char> zeros(end_byte - begin_byte);
732 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700733 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700734 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700735 return true;
736}
737
Darin Petkovd7061ab2010-10-06 14:37:09 -0700738bool DeltaPerformer::ExtractSignatureMessage(
739 const DeltaArchiveManifest_InstallOperation& operation) {
740 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
741 !manifest_.has_signatures_offset() ||
742 manifest_.signatures_offset() != operation.data_offset()) {
743 return false;
744 }
745 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
746 manifest_.signatures_size() == operation.data_length());
747 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
748 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
749 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700750 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700751 buffer_.begin(),
752 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700753
754 // Save the signature blob because if the update is interrupted after the
755 // download phase we don't go through this path anymore. Some alternatives to
756 // consider:
757 //
758 // 1. On resume, re-download the signature blob from the server and re-verify
759 // it.
760 //
761 // 2. Verify the signature as soon as it's received and don't checkpoint the
762 // blob and the signed sha-256 context.
763 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
764 string(&signatures_message_data_[0],
765 signatures_message_data_.size())))
766 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700767 // The hash of all data consumed so far should be verified against the signed
768 // hash.
769 signed_hash_context_ = hash_calculator_.GetContext();
770 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
771 signed_hash_context_))
772 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700773 LOG(INFO) << "Extracted signature data of size "
774 << manifest_.signatures_size() << " at "
775 << manifest_.signatures_offset();
776 return true;
777}
778
David Zeuthena99981f2013-04-29 13:42:47 -0700779ErrorCode DeltaPerformer::ValidateMetadataSignature(
Jay Srinivasanf4318702012-09-24 11:56:24 -0700780 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700781
Jay Srinivasanf4318702012-09-24 11:56:24 -0700782 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800783 if (install_plan_->hash_checks_mandatory) {
784 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700785 return kErrorCodeDownloadMetadataSignatureMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800786 }
787
788 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700789 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
David Zeuthena99981f2013-04-29 13:42:47 -0700790 SendUmaStat(kErrorCodeDownloadMetadataSignatureMissingError);
791 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700792 }
793
794 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700795 vector<char> metadata_signature;
796 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
797 &metadata_signature)) {
798 LOG(ERROR) << "Unable to decode base64 metadata signature: "
799 << install_plan_->metadata_signature;
David Zeuthena99981f2013-04-29 13:42:47 -0700800 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700801 }
802
Jay Srinivasanf4318702012-09-24 11:56:24 -0700803 vector<char> expected_metadata_hash;
804 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700805 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700806 &expected_metadata_hash)) {
807 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
David Zeuthena99981f2013-04-29 13:42:47 -0700808 return kErrorCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700809 }
810
Jay Srinivasanf4318702012-09-24 11:56:24 -0700811 OmahaHashCalculator metadata_hasher;
812 metadata_hasher.Update(metadata, metadata_size);
813 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700814 LOG(ERROR) << "Unable to compute actual hash of manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700815 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700816 }
817
Jay Srinivasanf4318702012-09-24 11:56:24 -0700818 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
819 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
820 if (calculated_metadata_hash.empty()) {
821 LOG(ERROR) << "Computed actual hash of metadata is empty.";
David Zeuthena99981f2013-04-29 13:42:47 -0700822 return kErrorCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700823 }
824
Jay Srinivasanf4318702012-09-24 11:56:24 -0700825 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700826 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700827 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700828 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700829 utils::HexDumpVector(calculated_metadata_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700830 return kErrorCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700831 }
832
833 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
David Zeuthena99981f2013-04-29 13:42:47 -0700834 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700835}
836
Gilad Arnold21504f02013-05-24 08:51:22 -0700837ErrorCode DeltaPerformer::ValidateManifest() {
838 // Ensure that a full update does not contain old partition hashes, which is
839 // indicative of a delta.
840 //
841 // TODO(garnold) in general, the presence of an old partition hash should be
842 // the sole indicator for a delta update, as we would generally like update
843 // payloads to be self contained and not assume an Omaha response to tell us
844 // that. However, since this requires some massive reengineering of the update
845 // flow (making filesystem copying happen conditionally only *after*
846 // downloading and parsing of the update manifest) we'll put it off for now.
847 // See chromium-os:7597 for further discussion.
848 if (install_plan_->is_full_update &&
849 (manifest_.has_old_kernel_info() || manifest_.has_old_rootfs_info())) {
850 LOG(ERROR) << "Purported full payload contains old partition "
851 "hash(es), aborting update";
852 return kErrorCodePayloadMismatchedType;
853 }
854
855 // TODO(garnold) we should be adding more and more manifest checks, such as
856 // partition boundaries etc (see chromium-os:37661).
857
858 return kErrorCodeSuccess;
859}
860
David Zeuthena99981f2013-04-29 13:42:47 -0700861ErrorCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800862 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700863
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700864 if (!operation.data_sha256_hash().size()) {
865 if (!operation.data_length()) {
866 // Operations that do not have any data blob won't have any operation hash
867 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700868 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800869 // has already been validated. This is true for both HTTP and HTTPS cases.
David Zeuthena99981f2013-04-29 13:42:47 -0700870 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700871 }
872
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800873 // No hash is present for an operation that has data blobs. This shouldn't
874 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700875 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800876 // hashes. So if it happens it means either we've turned operation hash
877 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700878 // One caveat though: The last operation is a dummy signature operation
879 // that doesn't have a hash at the time the manifest is created. So we
880 // should not complaint about that operation. This operation can be
881 // recognized by the fact that it's offset is mentioned in the manifest.
882 if (manifest_.signatures_offset() &&
883 manifest_.signatures_offset() == operation.data_offset()) {
884 LOG(INFO) << "Skipping hash verification for signature operation "
885 << next_operation_num_ + 1;
886 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800887 if (install_plan_->hash_checks_mandatory) {
888 LOG(ERROR) << "Missing mandatory operation hash for operation "
889 << next_operation_num_ + 1;
David Zeuthena99981f2013-04-29 13:42:47 -0700890 return kErrorCodeDownloadOperationHashMissingError;
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800891 }
892
893 // For non-mandatory cases, just send a UMA stat.
894 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
895 << " as there's no operation hash in manifest";
David Zeuthena99981f2013-04-29 13:42:47 -0700896 SendUmaStat(kErrorCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700897 }
David Zeuthena99981f2013-04-29 13:42:47 -0700898 return kErrorCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700899 }
900
901 vector<char> expected_op_hash;
902 expected_op_hash.assign(operation.data_sha256_hash().data(),
903 (operation.data_sha256_hash().data() +
904 operation.data_sha256_hash().size()));
905
906 OmahaHashCalculator operation_hasher;
907 operation_hasher.Update(&buffer_[0], operation.data_length());
908 if (!operation_hasher.Finalize()) {
909 LOG(ERROR) << "Unable to compute actual hash of operation "
910 << next_operation_num_;
David Zeuthena99981f2013-04-29 13:42:47 -0700911 return kErrorCodeDownloadOperationHashVerificationError;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700912 }
913
914 vector<char> calculated_op_hash = operation_hasher.raw_hash();
915 if (calculated_op_hash != expected_op_hash) {
916 LOG(ERROR) << "Hash verification failed for operation "
917 << next_operation_num_ << ". Expected hash = ";
918 utils::HexDumpVector(expected_op_hash);
919 LOG(ERROR) << "Calculated hash over " << operation.data_length()
920 << " bytes at offset: " << operation.data_offset() << " = ";
921 utils::HexDumpVector(calculated_op_hash);
David Zeuthena99981f2013-04-29 13:42:47 -0700922 return kErrorCodeDownloadOperationHashMismatch;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700923 }
924
David Zeuthena99981f2013-04-29 13:42:47 -0700925 return kErrorCodeSuccess;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700926}
927
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700928#define TEST_AND_RETURN_VAL(_retval, _condition) \
929 do { \
930 if (!(_condition)) { \
931 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
932 return _retval; \
933 } \
934 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700935
David Zeuthena99981f2013-04-29 13:42:47 -0700936ErrorCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700937 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700938 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700939 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700940
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700941 // Verifies the download size.
David Zeuthena99981f2013-04-29 13:42:47 -0700942 TEST_AND_RETURN_VAL(kErrorCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700943 update_check_response_size ==
944 manifest_metadata_size_ + buffer_offset_);
945
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700946 // Verifies the payload hash.
947 const string& payload_hash_data = hash_calculator_.hash();
David Zeuthena99981f2013-04-29 13:42:47 -0700948 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700949 !payload_hash_data.empty());
David Zeuthena99981f2013-04-29 13:42:47 -0700950 TEST_AND_RETURN_VAL(kErrorCodePayloadHashMismatchError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700951 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700952
Darin Petkov437adc42010-10-07 13:12:24 -0700953 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700954 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700955 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
David Zeuthena99981f2013-04-29 13:42:47 -0700956 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700957 }
David Zeuthena99981f2013-04-29 13:42:47 -0700958 TEST_AND_RETURN_VAL(kErrorCodeSignedDeltaPayloadExpectedError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700959 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700960 vector<char> signed_hash_data;
David Zeuthena99981f2013-04-29 13:42:47 -0700961 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700962 PayloadSigner::VerifySignature(
963 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700964 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700965 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700966 OmahaHashCalculator signed_hasher;
David Zeuthena99981f2013-04-29 13:42:47 -0700967 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700968 signed_hasher.SetContext(signed_hash_context_));
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.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700971 vector<char> hash_data = signed_hasher.raw_hash();
972 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -0700973 TEST_AND_RETURN_VAL(kErrorCodeDownloadPayloadPubKeyVerificationError,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700974 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700975 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700976 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700977 "Attached Signature:";
978 utils::HexDumpVector(signed_hash_data);
979 LOG(ERROR) << "Computed Signature:";
980 utils::HexDumpVector(hash_data);
David Zeuthena99981f2013-04-29 13:42:47 -0700981 return kErrorCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700982 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800983
984 // At this point, we are guaranteed to have downloaded a full payload, i.e
985 // the one whose size matches the size mentioned in Omaha response. If any
986 // errors happen after this, it's likely a problem with the payload itself or
987 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800988 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800989 system_state_->payload_state()->DownloadComplete();
990
David Zeuthena99981f2013-04-29 13:42:47 -0700991 return kErrorCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700992}
993
Darin Petkov3aefa862010-12-07 14:45:00 -0800994bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
995 vector<char>* kernel_hash,
996 uint64_t* rootfs_size,
997 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -0700998 TEST_AND_RETURN_FALSE(manifest_valid_ &&
999 manifest_.has_new_kernel_info() &&
1000 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001001 *kernel_size = manifest_.new_kernel_info().size();
1002 *rootfs_size = manifest_.new_rootfs_info().size();
1003 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1004 manifest_.new_kernel_info().hash().end());
1005 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1006 manifest_.new_rootfs_info().hash().end());
1007 kernel_hash->swap(new_kernel_hash);
1008 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001009 return true;
1010}
1011
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001012namespace {
1013void LogVerifyError(bool is_kern,
1014 const string& local_hash,
1015 const string& expected_hash) {
1016 const char* type = is_kern ? "kernel" : "rootfs";
1017 LOG(ERROR) << "This is a server-side error due to "
1018 << "mismatched delta update image!";
1019 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1020 << "update that must be applied over a " << type << " with "
1021 << "a specific checksum, but the " << type << " we're starting "
1022 << "with doesn't have that checksum! This means that "
1023 << "the delta I've been given doesn't match my existing "
1024 << "system. The " << type << " partition I have has hash: "
1025 << local_hash << " but the update expected me to have "
1026 << expected_hash << " .";
1027 if (is_kern) {
1028 LOG(INFO) << "To get the checksum of a kernel partition on a "
1029 << "booted machine, run this command (change /dev/sda2 "
1030 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1031 << "openssl dgst -sha256 -binary | openssl base64";
1032 } else {
1033 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1034 << "booted machine, run this command (change /dev/sda3 "
1035 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1036 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1037 << "| sed 's/[^0-9]*//') / 256 )) | "
1038 << "openssl dgst -sha256 -binary | openssl base64";
1039 }
1040 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1041 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1042}
1043
1044string StringForHashBytes(const void* bytes, size_t size) {
1045 string ret;
1046 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1047 ret = "<unknown>";
1048 }
1049 return ret;
1050}
1051} // namespace
1052
Darin Petkov698d0412010-10-13 10:59:44 -07001053bool DeltaPerformer::VerifySourcePartitions() {
1054 LOG(INFO) << "Verifying source partitions.";
1055 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001056 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001057 if (manifest_.has_old_kernel_info()) {
1058 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001059 bool valid =
1060 !install_plan_->kernel_hash.empty() &&
1061 install_plan_->kernel_hash.size() == info.hash().size() &&
1062 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001063 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001064 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001065 if (!valid) {
1066 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001067 StringForHashBytes(install_plan_->kernel_hash.data(),
1068 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001069 StringForHashBytes(info.hash().data(),
1070 info.hash().size()));
1071 }
1072 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001073 }
1074 if (manifest_.has_old_rootfs_info()) {
1075 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001076 bool valid =
1077 !install_plan_->rootfs_hash.empty() &&
1078 install_plan_->rootfs_hash.size() == info.hash().size() &&
1079 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001080 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001081 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001082 if (!valid) {
1083 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001084 StringForHashBytes(install_plan_->rootfs_hash.data(),
1085 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001086 StringForHashBytes(info.hash().data(),
1087 info.hash().size()));
1088 }
1089 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001090 }
1091 return true;
1092}
1093
Darin Petkov437adc42010-10-07 13:12:24 -07001094void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1095 hash_calculator_.Update(&buffer_[0], count);
Darin Petkov7f2ec752013-04-03 14:45:19 +02001096 // Copy the remainder data into a temporary vector first to ensure that any
1097 // unused memory in the updated |buffer_| will be released.
1098 vector<char> temp(buffer_.begin() + count, buffer_.end());
1099 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001100}
1101
Darin Petkov0406e402010-10-06 21:33:11 -07001102bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1103 string update_check_response_hash) {
1104 int64_t next_operation = kUpdateStateOperationInvalid;
1105 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1106 &next_operation) &&
1107 next_operation != kUpdateStateOperationInvalid &&
1108 next_operation > 0);
1109
1110 string interrupted_hash;
1111 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1112 &interrupted_hash) &&
1113 !interrupted_hash.empty() &&
1114 interrupted_hash == update_check_response_hash);
1115
Darin Petkov61426142010-10-08 11:04:55 -07001116 int64_t resumed_update_failures;
1117 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1118 &resumed_update_failures) ||
1119 resumed_update_failures <= kMaxResumedUpdateFailures);
1120
Darin Petkov0406e402010-10-06 21:33:11 -07001121 // Sanity check the rest.
1122 int64_t next_data_offset = -1;
1123 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1124 &next_data_offset) &&
1125 next_data_offset >= 0);
1126
Darin Petkov437adc42010-10-07 13:12:24 -07001127 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001128 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001129 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1130 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001131
1132 int64_t manifest_metadata_size = 0;
1133 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1134 &manifest_metadata_size) &&
1135 manifest_metadata_size > 0);
1136
1137 return true;
1138}
1139
Darin Petkov9b230572010-10-08 10:20:09 -07001140bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001141 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1142 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001143 if (!quick) {
1144 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1145 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1146 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1147 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001148 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001149 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001150 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001151 }
Darin Petkov73058b42010-10-06 16:32:19 -07001152 return true;
1153}
1154
1155bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001156 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001157 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001158 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001159 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001160 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001161 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001162 hash_calculator_.GetContext()));
1163 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1164 buffer_offset_));
1165 last_updated_buffer_offset_ = buffer_offset_;
1166 }
Darin Petkov73058b42010-10-06 16:32:19 -07001167 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1168 next_operation_num_));
1169 return true;
1170}
1171
Darin Petkov9b230572010-10-08 10:20:09 -07001172bool DeltaPerformer::PrimeUpdateState() {
1173 CHECK(manifest_valid_);
1174 block_size_ = manifest_.block_size();
1175
1176 int64_t next_operation = kUpdateStateOperationInvalid;
1177 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1178 next_operation == kUpdateStateOperationInvalid ||
1179 next_operation <= 0) {
1180 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001181 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001182 return true;
1183 }
1184 next_operation_num_ = next_operation;
1185
1186 // Resuming an update -- load the rest of the update state.
1187 int64_t next_data_offset = -1;
1188 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1189 &next_data_offset) &&
1190 next_data_offset >= 0);
1191 buffer_offset_ = next_data_offset;
1192
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001193 // The signed hash context and the signature blob may be empty if the
1194 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001195 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1196 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001197 string signature_blob;
1198 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1199 signatures_message_data_.assign(signature_blob.begin(),
1200 signature_blob.end());
1201 }
Darin Petkov9b230572010-10-08 10:20:09 -07001202
1203 string hash_context;
1204 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1205 &hash_context) &&
1206 hash_calculator_.SetContext(hash_context));
1207
1208 int64_t manifest_metadata_size = 0;
1209 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1210 &manifest_metadata_size) &&
1211 manifest_metadata_size > 0);
1212 manifest_metadata_size_ = manifest_metadata_size;
1213
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001214 // Advance the download progress to reflect what doesn't need to be
1215 // re-downloaded.
1216 total_bytes_received_ += buffer_offset_;
1217
Darin Petkov61426142010-10-08 11:04:55 -07001218 // Speculatively count the resume as a failure.
1219 int64_t resumed_update_failures;
1220 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1221 resumed_update_failures++;
1222 } else {
1223 resumed_update_failures = 1;
1224 }
1225 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001226 return true;
1227}
1228
David Zeuthena99981f2013-04-29 13:42:47 -07001229void DeltaPerformer::SendUmaStat(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001230 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001231}
1232
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001233} // namespace chromeos_update_engine