blob: 12f0e20894554e9cac359e287bb453a6e93494f0 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -07006
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07007#include <endian.h>
8#include <errno.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -07009
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070010#include <algorithm>
11#include <cstring>
12#include <string>
13#include <vector>
14
Chris Masoned903c3b2011-05-12 15:35:46 -070015#include <base/memory/scoped_ptr.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070016#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040017#include <base/stringprintf.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070018#include <google/protobuf/repeated_field.h>
19
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070020#include "update_engine/bzip_extent_writer.h"
21#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070022#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070023#include "update_engine/extent_writer.h"
24#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070025#include "update_engine/payload_signer.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080026#include "update_engine/payload_state_interface.h"
Darin Petkov73058b42010-10-06 16:32:19 -070027#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070028#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070029#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070030#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070031
32using std::min;
33using std::string;
34using std::vector;
35using google::protobuf::RepeatedPtrField;
36
37namespace chromeos_update_engine {
38
Jay Srinivasanf4318702012-09-24 11:56:24 -070039const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
40const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Darin Petkovabc7bc02011-02-23 14:39:43 -080041const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
42 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080043const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
44const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
45const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
46const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080047
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070048namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070049const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070050const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070051
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070052// Converts extents to a human-readable string, for use by DumpUpdateProto().
53string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
54 string ret;
55 for (int i = 0; i < extents.size(); i++) {
56 const Extent& extent = extents.Get(i);
57 if (extent.start_block() == kSparseHole) {
58 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
59 } else {
60 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
61 extent.start_block(), extent.num_blocks());
62 }
63 }
64 if (!ret.empty()) {
65 DCHECK_GT(ret.size(), static_cast<size_t>(1));
66 ret.resize(ret.size() - 2);
67 }
68 return ret;
69}
70
71// LOGs a DeltaArchiveManifest object. Useful for debugging.
72void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
73 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070074 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070075 for (int i = 0; i < (manifest.install_operations_size() +
76 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070077 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070078 i < manifest.install_operations_size() ?
79 manifest.install_operations(i) :
80 manifest.kernel_install_operations(
81 i - manifest.install_operations_size());
82 if (i == 0)
83 LOG(INFO) << " Rootfs ops:";
84 else if (i == manifest.install_operations_size())
85 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070086 LOG(INFO) << " operation(" << i << ")";
87 LOG(INFO) << " type: "
88 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
89 if (op.has_data_offset())
90 LOG(INFO) << " data_offset: " << op.data_offset();
91 if (op.has_data_length())
92 LOG(INFO) << " data_length: " << op.data_length();
93 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
94 if (op.has_src_length())
95 LOG(INFO) << " src_length: " << op.src_length();
96 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
97 if (op.has_dst_length())
98 LOG(INFO) << " dst_length: " << op.dst_length();
99 }
100}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700101
102// Opens path for read/write, put the fd into *fd. On success returns true
103// and sets *err to 0. On failure, returns false and sets *err to errno.
104bool OpenFile(const char* path, int* fd, int* err) {
105 if (*fd != -1) {
106 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
107 *err = EINVAL;
108 return false;
109 }
110 *fd = open(path, O_RDWR, 000);
111 if (*fd < 0) {
112 *err = errno;
113 PLOG(ERROR) << "Unable to open file " << path;
114 return false;
115 }
116 *err = 0;
117 return true;
118}
119
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700120} // namespace {}
121
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800122
123// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
124// arithmetic.
125static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
126 return part * norm / total;
127}
128
129void DeltaPerformer::LogProgress(const char* message_prefix) {
130 // Format operations total count and percentage.
131 string total_operations_str("?");
132 string completed_percentage_str("");
133 if (num_total_operations_) {
134 total_operations_str = StringPrintf("%zu", num_total_operations_);
135 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
136 completed_percentage_str =
137 StringPrintf(" (%llu%%)",
138 IntRatio(next_operation_num_, num_total_operations_,
139 100));
140 }
141
142 // Format download total count and percentage.
143 size_t payload_size = install_plan_->payload_size;
144 string payload_size_str("?");
145 string downloaded_percentage_str("");
146 if (payload_size) {
147 payload_size_str = StringPrintf("%zu", payload_size);
148 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
149 downloaded_percentage_str =
150 StringPrintf(" (%llu%%)",
151 IntRatio(total_bytes_received_, payload_size, 100));
152 }
153
154 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
155 << "/" << total_operations_str << " operations"
156 << completed_percentage_str << ", " << total_bytes_received_
157 << "/" << payload_size_str << " bytes downloaded"
158 << downloaded_percentage_str << ", overall progress "
159 << overall_progress_ << "%";
160}
161
162void DeltaPerformer::UpdateOverallProgress(bool force_log,
163 const char* message_prefix) {
164 // Compute our download and overall progress.
165 unsigned new_overall_progress = 0;
166 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
167 progress_weight_dont_add_up);
168 // Only consider download progress if its total size is known; otherwise
169 // adjust the operations weight to compensate for the absence of download
170 // progress. Also, make sure to cap the download portion at
171 // kProgressDownloadWeight, in case we end up downloading more than we
172 // initially expected (this indicates a problem, but could generally happen).
173 // TODO(garnold) the correction of operations weight when we do not have the
174 // total payload size, as well as the conditional guard below, should both be
175 // eliminated once we ensure that the payload_size in the install plan is
176 // always given and is non-zero. This currently isn't the case during unit
177 // tests (see chromium-os:37969).
178 size_t payload_size = install_plan_->payload_size;
179 unsigned actual_operations_weight = kProgressOperationsWeight;
180 if (payload_size)
181 new_overall_progress += min(
182 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
183 kProgressDownloadWeight)),
184 kProgressDownloadWeight);
185 else
186 actual_operations_weight += kProgressDownloadWeight;
187
188 // Only add completed operations if their total number is known; we definitely
189 // expect an update to have at least one operation, so the expectation is that
190 // this will eventually reach |actual_operations_weight|.
191 if (num_total_operations_)
192 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
193 actual_operations_weight);
194
195 // Progress ratio cannot recede, unless our assumptions about the total
196 // payload size, total number of operations, or the monotonicity of progress
197 // is breached.
198 if (new_overall_progress < overall_progress_) {
199 LOG(WARNING) << "progress counter receded from " << overall_progress_
200 << "% down to " << new_overall_progress << "%; this is a bug";
201 force_log = true;
202 }
203 overall_progress_ = new_overall_progress;
204
205 // Update chunk index, log as needed: if forced by called, or we completed a
206 // progress chunk, or a timeout has expired.
207 base::Time curr_time = base::Time::Now();
208 unsigned curr_progress_chunk =
209 overall_progress_ * kProgressLogMaxChunks / 100;
210 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
211 curr_time > forced_progress_log_time_) {
212 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
213 LogProgress(message_prefix);
214 }
215 last_progress_chunk_ = curr_progress_chunk;
216}
217
218
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700219// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
220// it safely. Returns false otherwise.
221bool DeltaPerformer::IsIdempotentOperation(
222 const DeltaArchiveManifest_InstallOperation& op) {
223 if (op.src_extents_size() == 0) {
224 return true;
225 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700226 // When in doubt, it's safe to declare an op non-idempotent. Note that we
227 // could detect other types of idempotent operations here such as a MOVE that
228 // moves blocks onto themselves. However, we rely on the server to not send
229 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700230 ExtentRanges src_ranges;
231 src_ranges.AddRepeatedExtents(op.src_extents());
232 const uint64_t block_count = src_ranges.blocks();
233 src_ranges.SubtractRepeatedExtents(op.dst_extents());
234 return block_count == src_ranges.blocks();
235}
236
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700237int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700238 int err;
239 if (OpenFile(path, &fd_, &err))
240 path_ = path;
241 return -err;
242}
243
244bool DeltaPerformer::OpenKernel(const char* kernel_path) {
245 int err;
246 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
247 if (success)
248 kernel_path_ = kernel_path;
249 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700250}
251
252int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700253 int err = 0;
254 if (close(kernel_fd_) == -1) {
255 err = errno;
256 PLOG(ERROR) << "Unable to close kernel fd:";
257 }
258 if (close(fd_) == -1) {
259 err = errno;
260 PLOG(ERROR) << "Unable to close rootfs fd:";
261 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700262 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800263 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700264 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800265 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700266 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
267 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800268 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800269 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700270 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700271}
272
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700273namespace {
274
275void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
276 string sha256;
277 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
278 info.hash().size(),
279 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800280 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
281 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700282 } else {
283 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
284 }
285}
286
287void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
288 if (manifest.has_old_kernel_info())
289 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
290 if (manifest.has_old_rootfs_info())
291 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
292 if (manifest.has_new_kernel_info())
293 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
294 if (manifest.has_new_rootfs_info())
295 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
296}
297
298} // namespace {}
299
Jay Srinivasanf4318702012-09-24 11:56:24 -0700300uint64_t DeltaPerformer::GetManifestSizeOffset() {
301 // Manifest size is stored right after the magic string and the version.
302 return strlen(kDeltaMagic) + kDeltaVersionSize;
303}
304
305uint64_t DeltaPerformer::GetManifestOffset() {
306 // Actual manifest begins right after the manifest size field.
307 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
308}
309
310
Darin Petkov9574f7e2011-01-13 10:48:12 -0800311DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
312 const std::vector<char>& payload,
313 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700314 uint64_t* metadata_size,
315 ActionExitCode* error) {
316 *error = kActionCodeSuccess;
317
Jay Srinivasanf4318702012-09-24 11:56:24 -0700318 // manifest_offset is the byte offset where the manifest protobuf begins.
319 const uint64_t manifest_offset = GetManifestOffset();
320 if (payload.size() < manifest_offset) {
321 // Don't have enough bytes to even know the manifest size.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800322 return kMetadataParseInsufficientData;
323 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700324
Jay Srinivasanf4318702012-09-24 11:56:24 -0700325 // Validate the magic string.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800326 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
327 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700328 *error = kActionCodeDownloadInvalidMetadataMagicString;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800329 return kMetadataParseError;
330 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700331
332 // TODO(jaysri): Compare the version number and skip unknown manifest
333 // versions. We don't check the version at all today.
334
Jay Srinivasanf4318702012-09-24 11:56:24 -0700335 // Next, parse the manifest size.
336 uint64_t manifest_size;
337 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
338 manifest_size_size_mismatch);
339 memcpy(&manifest_size,
340 &payload[GetManifestSizeOffset()],
341 kDeltaManifestSizeSize);
342 manifest_size = be64toh(manifest_size); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700343
344 // Now, check if the metasize we computed matches what was passed in
345 // through Omaha Response.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700346 *metadata_size = manifest_offset + manifest_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700347
Jay Srinivasanf4318702012-09-24 11:56:24 -0700348 // If the metadata size is present in install plan, check for it immediately
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700349 // even before waiting for that many number of bytes to be downloaded
350 // in the payload. This will prevent any attack which relies on us downloading
Jay Srinivasanf4318702012-09-24 11:56:24 -0700351 // data beyond the expected metadata size.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800352 if (install_plan_->hash_checks_mandatory) {
353 if (install_plan_->metadata_size != *metadata_size) {
354 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
355 << install_plan_->metadata_size << ") is missing/incorrect."
356 << ", Actual = " << *metadata_size;
357 *error = kActionCodeDownloadInvalidMetadataSize;
358 return kMetadataParseError;
359 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700360 }
361
362 // Now that we have validated the metadata size, we should wait for the full
363 // metadata to be read in before we can parse it.
364 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800365 return kMetadataParseInsufficientData;
366 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700367
368 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700369 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700370 // that we just log once (instead of logging n times) if it takes n
371 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800372 if (install_plan_->metadata_size == *metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700373 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800374 } else {
375 // For mandatory-cases, we'd have already returned a kMetadataParseError
376 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
377 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
378 << install_plan_->metadata_size
379 << ") in Omaha response as validation is not mandatory. "
380 << "Trusting metadata size in payload = " << *metadata_size;
381 SendUmaStat(kActionCodeDownloadInvalidMetadataSize);
382 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700383
Jay Srinivasanf4318702012-09-24 11:56:24 -0700384 // We have the full metadata in |payload|. Verify its integrity
385 // and authenticity based on the information we have in Omaha response.
386 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700387 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800388 if (install_plan_->hash_checks_mandatory) {
389 LOG(ERROR) << "Mandatory metadata signature validation failed";
390 return kMetadataParseError;
391 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700392
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800393 // For non-mandatory cases, just send a UMA stat.
394 LOG(WARNING) << "Ignoring metadata signature validation failures";
395 SendUmaStat(*error);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700396 *error = kActionCodeSuccess;
397 }
398
Jay Srinivasanf4318702012-09-24 11:56:24 -0700399 // The metadata in |payload| is deemed valid. So, it's now safe to
400 // parse the protobuf.
401 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800402 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700403 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800404 return kMetadataParseError;
405 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800406 return kMetadataParseSuccess;
407}
408
409
Don Garrette410e0f2011-11-10 15:39:01 -0800410// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800411// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700412// and stores an action exit code in |error|.
413bool DeltaPerformer::Write(const void* bytes, size_t count,
414 ActionExitCode *error) {
415 *error = kActionCodeSuccess;
416
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700417 const char* c_bytes = reinterpret_cast<const char*>(bytes);
418 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800419 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800420
421 // Update the total byte downloaded count and the progress logs.
422 total_bytes_received_ += count;
423 UpdateOverallProgress(false, "Completed ");
424
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700425 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800426 MetadataParseResult result = ParsePayloadMetadata(buffer_,
427 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700428 &manifest_metadata_size_,
429 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800430 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800431 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800432 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800433 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800434 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700435 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700436 // Remove protobuf and header info from buffer_, so buffer_ contains
437 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700438 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700439 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700440 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700441 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700442 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700443
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700444 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700445 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700446 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700447 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800448 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700449 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800450
451 num_rootfs_operations_ = manifest_.install_operations_size();
452 num_total_operations_ =
453 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
454 if (next_operation_num_ > 0)
455 UpdateOverallProgress(true, "Resuming after ");
456 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700457 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800458
459 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700460 // Check if we should cancel the current attempt for any reason.
461 // In this case, *error will have already been populated with the reason
462 // why we're cancelling.
463 if (system_state_->update_attempter()->ShouldCancel(error))
464 return false;
465
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800466 const bool is_kernel_partition =
467 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700468 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800469 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700470 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800471 next_operation_num_ - num_rootfs_operations_) :
472 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700473 if (!CanPerformInstallOperation(op)) {
474 // This means we don't have enough bytes received yet to carry out the
475 // next operation.
476 return true;
477 }
478
Jay Srinivasanf4318702012-09-24 11:56:24 -0700479 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700480 // Otherwise, keep the old behavior. This serves as a knob to disable
481 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800482 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
483 // we would have already failed in ParsePayloadMetadata method and thus not
484 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700485 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700486 // Note: Validate must be called only if CanPerformInstallOperation is
487 // called. Otherwise, we might be failing operations before even if there
488 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800489 *error = ValidateOperationHash(op);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700490 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800491 if (install_plan_->hash_checks_mandatory) {
492 LOG(ERROR) << "Mandatory operation hash check failed";
493 return false;
494 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700495
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800496 // For non-mandatory cases, just send a UMA stat.
497 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700498 SendUmaStat(*error);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800499 *error = kActionCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700500 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700501 }
502
Darin Petkov45580e42010-10-08 14:02:40 -0700503 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700504 ScopedTerminatorExitUnblocker exit_unblocker =
505 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700506 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700507 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
508 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700509 if (!PerformReplaceOperation(op, is_kernel_partition)) {
510 LOG(ERROR) << "Failed to perform replace operation "
511 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700512 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800513 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700514 }
515 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700516 if (!PerformMoveOperation(op, is_kernel_partition)) {
517 LOG(ERROR) << "Failed to perform move operation "
518 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700519 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800520 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700521 }
522 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700523 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
524 LOG(ERROR) << "Failed to perform bsdiff operation "
525 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700526 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800527 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700528 }
529 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800530
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700531 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800532 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700533 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700534 }
Don Garrette410e0f2011-11-10 15:39:01 -0800535 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700536}
537
538bool DeltaPerformer::CanPerformInstallOperation(
539 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
540 operation) {
541 // Move operations don't require any data blob, so they can always
542 // be performed
543 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
544 return true;
545
546 // See if we have the entire data blob in the buffer
547 if (operation.data_offset() < buffer_offset_) {
548 LOG(ERROR) << "we threw away data it seems?";
549 return false;
550 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700551
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700552 return (operation.data_offset() + operation.data_length()) <=
553 (buffer_offset_ + buffer_.size());
554}
555
556bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700557 const DeltaArchiveManifest_InstallOperation& operation,
558 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700559 CHECK(operation.type() == \
560 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
561 operation.type() == \
562 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
563
564 // Since we delete data off the beginning of the buffer as we use it,
565 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700566 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
567 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700568
Darin Petkov437adc42010-10-07 13:12:24 -0700569 // Extract the signature message if it's in this operation.
570 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700571
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700572 DirectExtentWriter direct_writer;
573 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
574 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700575
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700576 // Since bzip decompression is optional, we have a variable writer that will
577 // point to one of the ExtentWriter objects above.
578 ExtentWriter* writer = NULL;
579 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
580 writer = &zero_pad_writer;
581 } else if (operation.type() ==
582 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
583 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
584 writer = bzip_writer.get();
585 } else {
586 NOTREACHED();
587 }
588
589 // Create a vector of extents to pass to the ExtentWriter.
590 vector<Extent> extents;
591 for (int i = 0; i < operation.dst_extents_size(); i++) {
592 extents.push_back(operation.dst_extents(i));
593 }
594
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700595 int fd = is_kernel_partition ? kernel_fd_ : fd_;
596
597 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700598 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
599 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700600
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700601 // Update buffer
602 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700603 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700604 return true;
605}
606
607bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700608 const DeltaArchiveManifest_InstallOperation& operation,
609 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700610 // Calculate buffer size. Note, this function doesn't do a sliding
611 // window to copy in case the source and destination blocks overlap.
612 // If we wanted to do a sliding window, we could program the server
613 // to generate deltas that effectively did a sliding window.
614
615 uint64_t blocks_to_read = 0;
616 for (int i = 0; i < operation.src_extents_size(); i++)
617 blocks_to_read += operation.src_extents(i).num_blocks();
618
619 uint64_t blocks_to_write = 0;
620 for (int i = 0; i < operation.dst_extents_size(); i++)
621 blocks_to_write += operation.dst_extents(i).num_blocks();
622
623 DCHECK_EQ(blocks_to_write, blocks_to_read);
624 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700625
626 int fd = is_kernel_partition ? kernel_fd_ : fd_;
627
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700628 // Read in bytes.
629 ssize_t bytes_read = 0;
630 for (int i = 0; i < operation.src_extents_size(); i++) {
631 ssize_t bytes_read_this_iteration = 0;
632 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700633 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700634 &buf[bytes_read],
635 extent.num_blocks() * block_size_,
636 extent.start_block() * block_size_,
637 &bytes_read_this_iteration));
638 TEST_AND_RETURN_FALSE(
639 bytes_read_this_iteration ==
640 static_cast<ssize_t>(extent.num_blocks() * block_size_));
641 bytes_read += bytes_read_this_iteration;
642 }
643
Darin Petkov45580e42010-10-08 14:02:40 -0700644 // If this is a non-idempotent operation, request a delayed exit and clear the
645 // update state in case the operation gets interrupted. Do this as late as
646 // possible.
647 if (!IsIdempotentOperation(operation)) {
648 Terminator::set_exit_blocked(true);
649 ResetUpdateProgress(prefs_, true);
650 }
651
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700652 // Write bytes out.
653 ssize_t bytes_written = 0;
654 for (int i = 0; i < operation.dst_extents_size(); i++) {
655 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700656 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700657 &buf[bytes_written],
658 extent.num_blocks() * block_size_,
659 extent.start_block() * block_size_));
660 bytes_written += extent.num_blocks() * block_size_;
661 }
662 DCHECK_EQ(bytes_written, bytes_read);
663 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
664 return true;
665}
666
667bool DeltaPerformer::ExtentsToBsdiffPositionsString(
668 const RepeatedPtrField<Extent>& extents,
669 uint64_t block_size,
670 uint64_t full_length,
671 string* positions_string) {
672 string ret;
673 uint64_t length = 0;
674 for (int i = 0; i < extents.size(); i++) {
675 Extent extent = extents.Get(i);
676 int64_t start = extent.start_block();
677 uint64_t this_length = min(full_length - length,
678 extent.num_blocks() * block_size);
679 if (start == static_cast<int64_t>(kSparseHole))
680 start = -1;
681 else
682 start *= block_size;
683 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
684 length += this_length;
685 }
686 TEST_AND_RETURN_FALSE(length == full_length);
687 if (!ret.empty())
688 ret.resize(ret.size() - 1); // Strip trailing comma off
689 *positions_string = ret;
690 return true;
691}
692
693bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700694 const DeltaArchiveManifest_InstallOperation& operation,
695 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700696 // Since we delete data off the beginning of the buffer as we use it,
697 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700698 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
699 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700700
701 string input_positions;
702 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
703 block_size_,
704 operation.src_length(),
705 &input_positions));
706 string output_positions;
707 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
708 block_size_,
709 operation.dst_length(),
710 &output_positions));
711
712 string temp_filename;
713 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
714 &temp_filename,
715 NULL));
716 ScopedPathUnlinker path_unlinker(temp_filename);
717 {
718 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
719 ScopedFdCloser fd_closer(&fd);
720 TEST_AND_RETURN_FALSE(
721 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
722 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700723
Darin Petkov7f2ec752013-04-03 14:45:19 +0200724 // Update the buffer to release the patch data memory as soon as the patch
725 // file is written out.
726 buffer_offset_ += operation.data_length();
727 DiscardBufferHeadBytes(operation.data_length());
728
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700729 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700730 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700731
Darin Petkov45580e42010-10-08 14:02:40 -0700732 // If this is a non-idempotent operation, request a delayed exit and clear the
733 // update state in case the operation gets interrupted. Do this as late as
734 // possible.
735 if (!IsIdempotentOperation(operation)) {
736 Terminator::set_exit_blocked(true);
737 ResetUpdateProgress(prefs_, true);
738 }
739
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700740 vector<string> cmd;
741 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700742 cmd.push_back(path);
743 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700744 cmd.push_back(temp_filename);
745 cmd.push_back(input_positions);
746 cmd.push_back(output_positions);
747 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700748 TEST_AND_RETURN_FALSE(
749 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700750 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700751 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700752 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700753 TEST_AND_RETURN_FALSE(return_code == 0);
754
755 if (operation.dst_length() % block_size_) {
756 // Zero out rest of final block.
757 // TODO(adlr): build this into bspatch; it's more efficient that way.
758 const Extent& last_extent =
759 operation.dst_extents(operation.dst_extents_size() - 1);
760 const uint64_t end_byte =
761 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
762 const uint64_t begin_byte =
763 end_byte - (block_size_ - operation.dst_length() % block_size_);
764 vector<char> zeros(end_byte - begin_byte);
765 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700766 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700767 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700768 return true;
769}
770
Darin Petkovd7061ab2010-10-06 14:37:09 -0700771bool DeltaPerformer::ExtractSignatureMessage(
772 const DeltaArchiveManifest_InstallOperation& operation) {
773 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
774 !manifest_.has_signatures_offset() ||
775 manifest_.signatures_offset() != operation.data_offset()) {
776 return false;
777 }
778 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
779 manifest_.signatures_size() == operation.data_length());
780 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
781 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
782 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700783 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700784 buffer_.begin(),
785 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700786
787 // Save the signature blob because if the update is interrupted after the
788 // download phase we don't go through this path anymore. Some alternatives to
789 // consider:
790 //
791 // 1. On resume, re-download the signature blob from the server and re-verify
792 // it.
793 //
794 // 2. Verify the signature as soon as it's received and don't checkpoint the
795 // blob and the signed sha-256 context.
796 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
797 string(&signatures_message_data_[0],
798 signatures_message_data_.size())))
799 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700800 // The hash of all data consumed so far should be verified against the signed
801 // hash.
802 signed_hash_context_ = hash_calculator_.GetContext();
803 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
804 signed_hash_context_))
805 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700806 LOG(INFO) << "Extracted signature data of size "
807 << manifest_.signatures_size() << " at "
808 << manifest_.signatures_offset();
809 return true;
810}
811
Jay Srinivasanf4318702012-09-24 11:56:24 -0700812ActionExitCode DeltaPerformer::ValidateMetadataSignature(
813 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700814
Jay Srinivasanf4318702012-09-24 11:56:24 -0700815 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800816 if (install_plan_->hash_checks_mandatory) {
817 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
818 return kActionCodeDownloadMetadataSignatureMissingError;
819 }
820
821 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700822 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700823 SendUmaStat(kActionCodeDownloadMetadataSignatureMissingError);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700824 return kActionCodeSuccess;
825 }
826
827 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700828 vector<char> metadata_signature;
829 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
830 &metadata_signature)) {
831 LOG(ERROR) << "Unable to decode base64 metadata signature: "
832 << install_plan_->metadata_signature;
833 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700834 }
835
Jay Srinivasanf4318702012-09-24 11:56:24 -0700836 vector<char> expected_metadata_hash;
837 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700838 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700839 &expected_metadata_hash)) {
840 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
841 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700842 }
843
Jay Srinivasanf4318702012-09-24 11:56:24 -0700844 OmahaHashCalculator metadata_hasher;
845 metadata_hasher.Update(metadata, metadata_size);
846 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700847 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700848 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700849 }
850
Jay Srinivasanf4318702012-09-24 11:56:24 -0700851 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
852 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
853 if (calculated_metadata_hash.empty()) {
854 LOG(ERROR) << "Computed actual hash of metadata is empty.";
855 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700856 }
857
Jay Srinivasanf4318702012-09-24 11:56:24 -0700858 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700859 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700860 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700861 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700862 utils::HexDumpVector(calculated_metadata_hash);
863 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700864 }
865
866 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
867 return kActionCodeSuccess;
868}
869
870ActionExitCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800871 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700872
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700873 if (!operation.data_sha256_hash().size()) {
874 if (!operation.data_length()) {
875 // Operations that do not have any data blob won't have any operation hash
876 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700877 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800878 // has already been validated. This is true for both HTTP and HTTPS cases.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700879 return kActionCodeSuccess;
880 }
881
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800882 // No hash is present for an operation that has data blobs. This shouldn't
883 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700884 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800885 // hashes. So if it happens it means either we've turned operation hash
886 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700887 // One caveat though: The last operation is a dummy signature operation
888 // that doesn't have a hash at the time the manifest is created. So we
889 // should not complaint about that operation. This operation can be
890 // recognized by the fact that it's offset is mentioned in the manifest.
891 if (manifest_.signatures_offset() &&
892 manifest_.signatures_offset() == operation.data_offset()) {
893 LOG(INFO) << "Skipping hash verification for signature operation "
894 << next_operation_num_ + 1;
895 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800896 if (install_plan_->hash_checks_mandatory) {
897 LOG(ERROR) << "Missing mandatory operation hash for operation "
898 << next_operation_num_ + 1;
899 return kActionCodeDownloadOperationHashMissingError;
900 }
901
902 // For non-mandatory cases, just send a UMA stat.
903 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
904 << " as there's no operation hash in manifest";
905 SendUmaStat(kActionCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700906 }
907 return kActionCodeSuccess;
908 }
909
910 vector<char> expected_op_hash;
911 expected_op_hash.assign(operation.data_sha256_hash().data(),
912 (operation.data_sha256_hash().data() +
913 operation.data_sha256_hash().size()));
914
915 OmahaHashCalculator operation_hasher;
916 operation_hasher.Update(&buffer_[0], operation.data_length());
917 if (!operation_hasher.Finalize()) {
918 LOG(ERROR) << "Unable to compute actual hash of operation "
919 << next_operation_num_;
920 return kActionCodeDownloadOperationHashVerificationError;
921 }
922
923 vector<char> calculated_op_hash = operation_hasher.raw_hash();
924 if (calculated_op_hash != expected_op_hash) {
925 LOG(ERROR) << "Hash verification failed for operation "
926 << next_operation_num_ << ". Expected hash = ";
927 utils::HexDumpVector(expected_op_hash);
928 LOG(ERROR) << "Calculated hash over " << operation.data_length()
929 << " bytes at offset: " << operation.data_offset() << " = ";
930 utils::HexDumpVector(calculated_op_hash);
931 return kActionCodeDownloadOperationHashMismatch;
932 }
933
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700934 return kActionCodeSuccess;
935}
936
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700937#define TEST_AND_RETURN_VAL(_retval, _condition) \
938 do { \
939 if (!(_condition)) { \
940 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
941 return _retval; \
942 } \
943 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700944
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700945ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700946 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700947 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700948 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700949
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700950 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700951 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700952 update_check_response_size ==
953 manifest_metadata_size_ + buffer_offset_);
954
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700955 // Verifies the payload hash.
956 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700957 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700958 !payload_hash_data.empty());
959 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
960 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700961
Darin Petkov437adc42010-10-07 13:12:24 -0700962 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700963 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700964 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700965 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700966 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700967 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
968 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700969 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700970 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
971 PayloadSigner::VerifySignature(
972 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700973 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700974 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700975 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700976 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
977 signed_hasher.SetContext(signed_hash_context_));
978 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
979 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700980 vector<char> hash_data = signed_hasher.raw_hash();
981 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700982 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
983 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700984 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700985 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700986 "Attached Signature:";
987 utils::HexDumpVector(signed_hash_data);
988 LOG(ERROR) << "Computed Signature:";
989 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700990 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700991 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800992
993 // At this point, we are guaranteed to have downloaded a full payload, i.e
994 // the one whose size matches the size mentioned in Omaha response. If any
995 // errors happen after this, it's likely a problem with the payload itself or
996 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800997 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800998 system_state_->payload_state()->DownloadComplete();
999
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001000 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001001}
1002
Darin Petkov3aefa862010-12-07 14:45:00 -08001003bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
1004 vector<char>* kernel_hash,
1005 uint64_t* rootfs_size,
1006 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001007 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1008 manifest_.has_new_kernel_info() &&
1009 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001010 *kernel_size = manifest_.new_kernel_info().size();
1011 *rootfs_size = manifest_.new_rootfs_info().size();
1012 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1013 manifest_.new_kernel_info().hash().end());
1014 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1015 manifest_.new_rootfs_info().hash().end());
1016 kernel_hash->swap(new_kernel_hash);
1017 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001018 return true;
1019}
1020
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001021namespace {
1022void LogVerifyError(bool is_kern,
1023 const string& local_hash,
1024 const string& expected_hash) {
1025 const char* type = is_kern ? "kernel" : "rootfs";
1026 LOG(ERROR) << "This is a server-side error due to "
1027 << "mismatched delta update image!";
1028 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1029 << "update that must be applied over a " << type << " with "
1030 << "a specific checksum, but the " << type << " we're starting "
1031 << "with doesn't have that checksum! This means that "
1032 << "the delta I've been given doesn't match my existing "
1033 << "system. The " << type << " partition I have has hash: "
1034 << local_hash << " but the update expected me to have "
1035 << expected_hash << " .";
1036 if (is_kern) {
1037 LOG(INFO) << "To get the checksum of a kernel partition on a "
1038 << "booted machine, run this command (change /dev/sda2 "
1039 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1040 << "openssl dgst -sha256 -binary | openssl base64";
1041 } else {
1042 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1043 << "booted machine, run this command (change /dev/sda3 "
1044 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1045 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1046 << "| sed 's/[^0-9]*//') / 256 )) | "
1047 << "openssl dgst -sha256 -binary | openssl base64";
1048 }
1049 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1050 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1051}
1052
1053string StringForHashBytes(const void* bytes, size_t size) {
1054 string ret;
1055 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1056 ret = "<unknown>";
1057 }
1058 return ret;
1059}
1060} // namespace
1061
Darin Petkov698d0412010-10-13 10:59:44 -07001062bool DeltaPerformer::VerifySourcePartitions() {
1063 LOG(INFO) << "Verifying source partitions.";
1064 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001065 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001066 if (manifest_.has_old_kernel_info()) {
1067 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001068 bool valid =
1069 !install_plan_->kernel_hash.empty() &&
1070 install_plan_->kernel_hash.size() == info.hash().size() &&
1071 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001072 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001073 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001074 if (!valid) {
1075 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001076 StringForHashBytes(install_plan_->kernel_hash.data(),
1077 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001078 StringForHashBytes(info.hash().data(),
1079 info.hash().size()));
1080 }
1081 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001082 }
1083 if (manifest_.has_old_rootfs_info()) {
1084 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001085 bool valid =
1086 !install_plan_->rootfs_hash.empty() &&
1087 install_plan_->rootfs_hash.size() == info.hash().size() &&
1088 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001089 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001090 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001091 if (!valid) {
1092 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001093 StringForHashBytes(install_plan_->rootfs_hash.data(),
1094 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001095 StringForHashBytes(info.hash().data(),
1096 info.hash().size()));
1097 }
1098 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001099 }
1100 return true;
1101}
1102
Darin Petkov437adc42010-10-07 13:12:24 -07001103void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1104 hash_calculator_.Update(&buffer_[0], count);
Darin Petkov7f2ec752013-04-03 14:45:19 +02001105 // Copy the remainder data into a temporary vector first to ensure that any
1106 // unused memory in the updated |buffer_| will be released.
1107 vector<char> temp(buffer_.begin() + count, buffer_.end());
1108 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001109}
1110
Darin Petkov0406e402010-10-06 21:33:11 -07001111bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1112 string update_check_response_hash) {
1113 int64_t next_operation = kUpdateStateOperationInvalid;
1114 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1115 &next_operation) &&
1116 next_operation != kUpdateStateOperationInvalid &&
1117 next_operation > 0);
1118
1119 string interrupted_hash;
1120 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1121 &interrupted_hash) &&
1122 !interrupted_hash.empty() &&
1123 interrupted_hash == update_check_response_hash);
1124
Darin Petkov61426142010-10-08 11:04:55 -07001125 int64_t resumed_update_failures;
1126 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1127 &resumed_update_failures) ||
1128 resumed_update_failures <= kMaxResumedUpdateFailures);
1129
Darin Petkov0406e402010-10-06 21:33:11 -07001130 // Sanity check the rest.
1131 int64_t next_data_offset = -1;
1132 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1133 &next_data_offset) &&
1134 next_data_offset >= 0);
1135
Darin Petkov437adc42010-10-07 13:12:24 -07001136 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001137 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001138 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1139 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001140
1141 int64_t manifest_metadata_size = 0;
1142 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1143 &manifest_metadata_size) &&
1144 manifest_metadata_size > 0);
1145
1146 return true;
1147}
1148
Darin Petkov9b230572010-10-08 10:20:09 -07001149bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001150 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1151 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001152 if (!quick) {
1153 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1154 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1155 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1156 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001157 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001158 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001159 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001160 }
Darin Petkov73058b42010-10-06 16:32:19 -07001161 return true;
1162}
1163
1164bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001165 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001166 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001167 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001168 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001169 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001170 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001171 hash_calculator_.GetContext()));
1172 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1173 buffer_offset_));
1174 last_updated_buffer_offset_ = buffer_offset_;
1175 }
Darin Petkov73058b42010-10-06 16:32:19 -07001176 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1177 next_operation_num_));
1178 return true;
1179}
1180
Darin Petkov9b230572010-10-08 10:20:09 -07001181bool DeltaPerformer::PrimeUpdateState() {
1182 CHECK(manifest_valid_);
1183 block_size_ = manifest_.block_size();
1184
1185 int64_t next_operation = kUpdateStateOperationInvalid;
1186 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1187 next_operation == kUpdateStateOperationInvalid ||
1188 next_operation <= 0) {
1189 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001190 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001191 return true;
1192 }
1193 next_operation_num_ = next_operation;
1194
1195 // Resuming an update -- load the rest of the update state.
1196 int64_t next_data_offset = -1;
1197 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1198 &next_data_offset) &&
1199 next_data_offset >= 0);
1200 buffer_offset_ = next_data_offset;
1201
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001202 // The signed hash context and the signature blob may be empty if the
1203 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001204 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1205 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001206 string signature_blob;
1207 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1208 signatures_message_data_.assign(signature_blob.begin(),
1209 signature_blob.end());
1210 }
Darin Petkov9b230572010-10-08 10:20:09 -07001211
1212 string hash_context;
1213 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1214 &hash_context) &&
1215 hash_calculator_.SetContext(hash_context));
1216
1217 int64_t manifest_metadata_size = 0;
1218 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1219 &manifest_metadata_size) &&
1220 manifest_metadata_size > 0);
1221 manifest_metadata_size_ = manifest_metadata_size;
1222
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001223 // Advance the download progress to reflect what doesn't need to be
1224 // re-downloaded.
1225 total_bytes_received_ += buffer_offset_;
1226
Darin Petkov61426142010-10-08 11:04:55 -07001227 // Speculatively count the resume as a failure.
1228 int64_t resumed_update_failures;
1229 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1230 resumed_update_failures++;
1231 } else {
1232 resumed_update_failures = 1;
1233 }
1234 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001235 return true;
1236}
1237
Jay Srinivasanedce2832012-10-24 18:57:47 -07001238void DeltaPerformer::SendUmaStat(ActionExitCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001239 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001240}
1241
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001242} // namespace chromeos_update_engine