blob: 74e21e2ac43c1d07748a5040a4c69e2b906edda5 [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
724 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700725 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700726
Darin Petkov45580e42010-10-08 14:02:40 -0700727 // If this is a non-idempotent operation, request a delayed exit and clear the
728 // update state in case the operation gets interrupted. Do this as late as
729 // possible.
730 if (!IsIdempotentOperation(operation)) {
731 Terminator::set_exit_blocked(true);
732 ResetUpdateProgress(prefs_, true);
733 }
734
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700735 vector<string> cmd;
736 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700737 cmd.push_back(path);
738 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700739 cmd.push_back(temp_filename);
740 cmd.push_back(input_positions);
741 cmd.push_back(output_positions);
742 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700743 TEST_AND_RETURN_FALSE(
744 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700745 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700746 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700747 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700748 TEST_AND_RETURN_FALSE(return_code == 0);
749
750 if (operation.dst_length() % block_size_) {
751 // Zero out rest of final block.
752 // TODO(adlr): build this into bspatch; it's more efficient that way.
753 const Extent& last_extent =
754 operation.dst_extents(operation.dst_extents_size() - 1);
755 const uint64_t end_byte =
756 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
757 const uint64_t begin_byte =
758 end_byte - (block_size_ - operation.dst_length() % block_size_);
759 vector<char> zeros(end_byte - begin_byte);
760 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700761 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700762 }
763
764 // Update buffer.
765 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700766 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700767 return true;
768}
769
Darin Petkovd7061ab2010-10-06 14:37:09 -0700770bool DeltaPerformer::ExtractSignatureMessage(
771 const DeltaArchiveManifest_InstallOperation& operation) {
772 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
773 !manifest_.has_signatures_offset() ||
774 manifest_.signatures_offset() != operation.data_offset()) {
775 return false;
776 }
777 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
778 manifest_.signatures_size() == operation.data_length());
779 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
780 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
781 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700782 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700783 buffer_.begin(),
784 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700785
786 // Save the signature blob because if the update is interrupted after the
787 // download phase we don't go through this path anymore. Some alternatives to
788 // consider:
789 //
790 // 1. On resume, re-download the signature blob from the server and re-verify
791 // it.
792 //
793 // 2. Verify the signature as soon as it's received and don't checkpoint the
794 // blob and the signed sha-256 context.
795 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
796 string(&signatures_message_data_[0],
797 signatures_message_data_.size())))
798 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700799 // The hash of all data consumed so far should be verified against the signed
800 // hash.
801 signed_hash_context_ = hash_calculator_.GetContext();
802 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
803 signed_hash_context_))
804 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700805 LOG(INFO) << "Extracted signature data of size "
806 << manifest_.signatures_size() << " at "
807 << manifest_.signatures_offset();
808 return true;
809}
810
Jay Srinivasanf4318702012-09-24 11:56:24 -0700811ActionExitCode DeltaPerformer::ValidateMetadataSignature(
812 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700813
Jay Srinivasanf4318702012-09-24 11:56:24 -0700814 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800815 if (install_plan_->hash_checks_mandatory) {
816 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
817 return kActionCodeDownloadMetadataSignatureMissingError;
818 }
819
820 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700821 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700822 SendUmaStat(kActionCodeDownloadMetadataSignatureMissingError);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700823 return kActionCodeSuccess;
824 }
825
826 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700827 vector<char> metadata_signature;
828 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
829 &metadata_signature)) {
830 LOG(ERROR) << "Unable to decode base64 metadata signature: "
831 << install_plan_->metadata_signature;
832 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700833 }
834
Jay Srinivasanf4318702012-09-24 11:56:24 -0700835 vector<char> expected_metadata_hash;
836 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700837 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700838 &expected_metadata_hash)) {
839 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
840 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700841 }
842
Jay Srinivasanf4318702012-09-24 11:56:24 -0700843 OmahaHashCalculator metadata_hasher;
844 metadata_hasher.Update(metadata, metadata_size);
845 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700846 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700847 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700848 }
849
Jay Srinivasanf4318702012-09-24 11:56:24 -0700850 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
851 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
852 if (calculated_metadata_hash.empty()) {
853 LOG(ERROR) << "Computed actual hash of metadata is empty.";
854 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700855 }
856
Jay Srinivasanf4318702012-09-24 11:56:24 -0700857 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700858 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700859 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700860 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700861 utils::HexDumpVector(calculated_metadata_hash);
862 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700863 }
864
865 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
866 return kActionCodeSuccess;
867}
868
869ActionExitCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800870 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700871
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700872 if (!operation.data_sha256_hash().size()) {
873 if (!operation.data_length()) {
874 // Operations that do not have any data blob won't have any operation hash
875 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700876 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800877 // has already been validated. This is true for both HTTP and HTTPS cases.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700878 return kActionCodeSuccess;
879 }
880
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800881 // No hash is present for an operation that has data blobs. This shouldn't
882 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700883 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800884 // hashes. So if it happens it means either we've turned operation hash
885 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700886 // One caveat though: The last operation is a dummy signature operation
887 // that doesn't have a hash at the time the manifest is created. So we
888 // should not complaint about that operation. This operation can be
889 // recognized by the fact that it's offset is mentioned in the manifest.
890 if (manifest_.signatures_offset() &&
891 manifest_.signatures_offset() == operation.data_offset()) {
892 LOG(INFO) << "Skipping hash verification for signature operation "
893 << next_operation_num_ + 1;
894 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800895 if (install_plan_->hash_checks_mandatory) {
896 LOG(ERROR) << "Missing mandatory operation hash for operation "
897 << next_operation_num_ + 1;
898 return kActionCodeDownloadOperationHashMissingError;
899 }
900
901 // For non-mandatory cases, just send a UMA stat.
902 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
903 << " as there's no operation hash in manifest";
904 SendUmaStat(kActionCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700905 }
906 return kActionCodeSuccess;
907 }
908
909 vector<char> expected_op_hash;
910 expected_op_hash.assign(operation.data_sha256_hash().data(),
911 (operation.data_sha256_hash().data() +
912 operation.data_sha256_hash().size()));
913
914 OmahaHashCalculator operation_hasher;
915 operation_hasher.Update(&buffer_[0], operation.data_length());
916 if (!operation_hasher.Finalize()) {
917 LOG(ERROR) << "Unable to compute actual hash of operation "
918 << next_operation_num_;
919 return kActionCodeDownloadOperationHashVerificationError;
920 }
921
922 vector<char> calculated_op_hash = operation_hasher.raw_hash();
923 if (calculated_op_hash != expected_op_hash) {
924 LOG(ERROR) << "Hash verification failed for operation "
925 << next_operation_num_ << ". Expected hash = ";
926 utils::HexDumpVector(expected_op_hash);
927 LOG(ERROR) << "Calculated hash over " << operation.data_length()
928 << " bytes at offset: " << operation.data_offset() << " = ";
929 utils::HexDumpVector(calculated_op_hash);
930 return kActionCodeDownloadOperationHashMismatch;
931 }
932
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700933 return kActionCodeSuccess;
934}
935
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700936#define TEST_AND_RETURN_VAL(_retval, _condition) \
937 do { \
938 if (!(_condition)) { \
939 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
940 return _retval; \
941 } \
942 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700943
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700944ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700945 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700946 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700947 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700948
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700949 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700950 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700951 update_check_response_size ==
952 manifest_metadata_size_ + buffer_offset_);
953
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700954 // Verifies the payload hash.
955 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700956 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700957 !payload_hash_data.empty());
958 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
959 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700960
Darin Petkov437adc42010-10-07 13:12:24 -0700961 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700962 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700963 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700964 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700965 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700966 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
967 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700968 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700969 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
970 PayloadSigner::VerifySignature(
971 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700972 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700973 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700974 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700975 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
976 signed_hasher.SetContext(signed_hash_context_));
977 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
978 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700979 vector<char> hash_data = signed_hasher.raw_hash();
980 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700981 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
982 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700983 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700984 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700985 "Attached Signature:";
986 utils::HexDumpVector(signed_hash_data);
987 LOG(ERROR) << "Computed Signature:";
988 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700989 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700990 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800991
992 // At this point, we are guaranteed to have downloaded a full payload, i.e
993 // the one whose size matches the size mentioned in Omaha response. If any
994 // errors happen after this, it's likely a problem with the payload itself or
995 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800996 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800997 system_state_->payload_state()->DownloadComplete();
998
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700999 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001000}
1001
Darin Petkov3aefa862010-12-07 14:45:00 -08001002bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
1003 vector<char>* kernel_hash,
1004 uint64_t* rootfs_size,
1005 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001006 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1007 manifest_.has_new_kernel_info() &&
1008 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001009 *kernel_size = manifest_.new_kernel_info().size();
1010 *rootfs_size = manifest_.new_rootfs_info().size();
1011 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1012 manifest_.new_kernel_info().hash().end());
1013 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1014 manifest_.new_rootfs_info().hash().end());
1015 kernel_hash->swap(new_kernel_hash);
1016 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001017 return true;
1018}
1019
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001020namespace {
1021void LogVerifyError(bool is_kern,
1022 const string& local_hash,
1023 const string& expected_hash) {
1024 const char* type = is_kern ? "kernel" : "rootfs";
1025 LOG(ERROR) << "This is a server-side error due to "
1026 << "mismatched delta update image!";
1027 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1028 << "update that must be applied over a " << type << " with "
1029 << "a specific checksum, but the " << type << " we're starting "
1030 << "with doesn't have that checksum! This means that "
1031 << "the delta I've been given doesn't match my existing "
1032 << "system. The " << type << " partition I have has hash: "
1033 << local_hash << " but the update expected me to have "
1034 << expected_hash << " .";
1035 if (is_kern) {
1036 LOG(INFO) << "To get the checksum of a kernel partition on a "
1037 << "booted machine, run this command (change /dev/sda2 "
1038 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1039 << "openssl dgst -sha256 -binary | openssl base64";
1040 } else {
1041 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1042 << "booted machine, run this command (change /dev/sda3 "
1043 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1044 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1045 << "| sed 's/[^0-9]*//') / 256 )) | "
1046 << "openssl dgst -sha256 -binary | openssl base64";
1047 }
1048 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1049 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1050}
1051
1052string StringForHashBytes(const void* bytes, size_t size) {
1053 string ret;
1054 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1055 ret = "<unknown>";
1056 }
1057 return ret;
1058}
1059} // namespace
1060
Darin Petkov698d0412010-10-13 10:59:44 -07001061bool DeltaPerformer::VerifySourcePartitions() {
1062 LOG(INFO) << "Verifying source partitions.";
1063 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001064 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001065 if (manifest_.has_old_kernel_info()) {
1066 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001067 bool valid =
1068 !install_plan_->kernel_hash.empty() &&
1069 install_plan_->kernel_hash.size() == info.hash().size() &&
1070 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001071 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001072 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001073 if (!valid) {
1074 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001075 StringForHashBytes(install_plan_->kernel_hash.data(),
1076 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001077 StringForHashBytes(info.hash().data(),
1078 info.hash().size()));
1079 }
1080 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001081 }
1082 if (manifest_.has_old_rootfs_info()) {
1083 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001084 bool valid =
1085 !install_plan_->rootfs_hash.empty() &&
1086 install_plan_->rootfs_hash.size() == info.hash().size() &&
1087 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001088 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001089 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001090 if (!valid) {
1091 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001092 StringForHashBytes(install_plan_->rootfs_hash.data(),
1093 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001094 StringForHashBytes(info.hash().data(),
1095 info.hash().size()));
1096 }
1097 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001098 }
1099 return true;
1100}
1101
Darin Petkov437adc42010-10-07 13:12:24 -07001102void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1103 hash_calculator_.Update(&buffer_[0], count);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001104 buffer_.erase(buffer_.begin(), buffer_.begin() + count);
1105}
1106
Darin Petkov0406e402010-10-06 21:33:11 -07001107bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1108 string update_check_response_hash) {
1109 int64_t next_operation = kUpdateStateOperationInvalid;
1110 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1111 &next_operation) &&
1112 next_operation != kUpdateStateOperationInvalid &&
1113 next_operation > 0);
1114
1115 string interrupted_hash;
1116 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1117 &interrupted_hash) &&
1118 !interrupted_hash.empty() &&
1119 interrupted_hash == update_check_response_hash);
1120
Darin Petkov61426142010-10-08 11:04:55 -07001121 int64_t resumed_update_failures;
1122 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1123 &resumed_update_failures) ||
1124 resumed_update_failures <= kMaxResumedUpdateFailures);
1125
Darin Petkov0406e402010-10-06 21:33:11 -07001126 // Sanity check the rest.
1127 int64_t next_data_offset = -1;
1128 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1129 &next_data_offset) &&
1130 next_data_offset >= 0);
1131
Darin Petkov437adc42010-10-07 13:12:24 -07001132 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001133 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001134 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1135 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001136
1137 int64_t manifest_metadata_size = 0;
1138 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1139 &manifest_metadata_size) &&
1140 manifest_metadata_size > 0);
1141
1142 return true;
1143}
1144
Darin Petkov9b230572010-10-08 10:20:09 -07001145bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001146 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1147 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001148 if (!quick) {
1149 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1150 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1151 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1152 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001153 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001154 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001155 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001156 }
Darin Petkov73058b42010-10-06 16:32:19 -07001157 return true;
1158}
1159
1160bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001161 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001162 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001163 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001164 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001165 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001166 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001167 hash_calculator_.GetContext()));
1168 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1169 buffer_offset_));
1170 last_updated_buffer_offset_ = buffer_offset_;
1171 }
Darin Petkov73058b42010-10-06 16:32:19 -07001172 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1173 next_operation_num_));
1174 return true;
1175}
1176
Darin Petkov9b230572010-10-08 10:20:09 -07001177bool DeltaPerformer::PrimeUpdateState() {
1178 CHECK(manifest_valid_);
1179 block_size_ = manifest_.block_size();
1180
1181 int64_t next_operation = kUpdateStateOperationInvalid;
1182 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1183 next_operation == kUpdateStateOperationInvalid ||
1184 next_operation <= 0) {
1185 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001186 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001187 return true;
1188 }
1189 next_operation_num_ = next_operation;
1190
1191 // Resuming an update -- load the rest of the update state.
1192 int64_t next_data_offset = -1;
1193 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1194 &next_data_offset) &&
1195 next_data_offset >= 0);
1196 buffer_offset_ = next_data_offset;
1197
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001198 // The signed hash context and the signature blob may be empty if the
1199 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001200 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1201 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001202 string signature_blob;
1203 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1204 signatures_message_data_.assign(signature_blob.begin(),
1205 signature_blob.end());
1206 }
Darin Petkov9b230572010-10-08 10:20:09 -07001207
1208 string hash_context;
1209 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1210 &hash_context) &&
1211 hash_calculator_.SetContext(hash_context));
1212
1213 int64_t manifest_metadata_size = 0;
1214 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1215 &manifest_metadata_size) &&
1216 manifest_metadata_size > 0);
1217 manifest_metadata_size_ = manifest_metadata_size;
1218
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001219 // Advance the download progress to reflect what doesn't need to be
1220 // re-downloaded.
1221 total_bytes_received_ += buffer_offset_;
1222
Darin Petkov61426142010-10-08 11:04:55 -07001223 // Speculatively count the resume as a failure.
1224 int64_t resumed_update_failures;
1225 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1226 resumed_update_failures++;
1227 } else {
1228 resumed_update_failures = 1;
1229 }
1230 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001231 return true;
1232}
1233
Jay Srinivasanedce2832012-10-24 18:57:47 -07001234void DeltaPerformer::SendUmaStat(ActionExitCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001235 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001236}
1237
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001238} // namespace chromeos_update_engine