blob: a815e287d5d8790311dd1845b9128d5bdb134061 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/delta_performer.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -07006
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07007#include <endian.h>
8#include <errno.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -07009
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070010#include <algorithm>
11#include <cstring>
12#include <string>
13#include <vector>
14
Chris Masoned903c3b2011-05-12 15:35:46 -070015#include <base/memory/scoped_ptr.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070016#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040017#include <base/stringprintf.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070018#include <google/protobuf/repeated_field.h>
19
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070020#include "update_engine/bzip_extent_writer.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070021#include "update_engine/constants.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070022#include "update_engine/delta_diff_generator.h"
Andrew de los Reyes353777c2010-10-08 10:34:30 -070023#include "update_engine/extent_ranges.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070024#include "update_engine/extent_writer.h"
25#include "update_engine/graph_types.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070026#include "update_engine/payload_signer.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080027#include "update_engine/payload_state_interface.h"
Darin Petkov73058b42010-10-06 16:32:19 -070028#include "update_engine/prefs_interface.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070029#include "update_engine/subprocess.h"
Darin Petkov9c0baf82010-10-07 13:44:48 -070030#include "update_engine/terminator.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070031#include "update_engine/update_attempter.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070032
33using std::min;
34using std::string;
35using std::vector;
36using google::protobuf::RepeatedPtrField;
37
38namespace chromeos_update_engine {
39
Jay Srinivasanf4318702012-09-24 11:56:24 -070040const uint64_t DeltaPerformer::kDeltaVersionSize = 8;
41const uint64_t DeltaPerformer::kDeltaManifestSizeSize = 8;
Darin Petkovabc7bc02011-02-23 14:39:43 -080042const char DeltaPerformer::kUpdatePayloadPublicKeyPath[] =
43 "/usr/share/update_engine/update-payload-key.pub.pem";
Gilad Arnold8a86fa52013-01-15 12:35:05 -080044const unsigned DeltaPerformer::kProgressLogMaxChunks = 10;
45const unsigned DeltaPerformer::kProgressLogTimeoutSeconds = 30;
46const unsigned DeltaPerformer::kProgressDownloadWeight = 50;
47const unsigned DeltaPerformer::kProgressOperationsWeight = 50;
Darin Petkovabc7bc02011-02-23 14:39:43 -080048
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070049namespace {
Darin Petkov73058b42010-10-06 16:32:19 -070050const int kUpdateStateOperationInvalid = -1;
Darin Petkov61426142010-10-08 11:04:55 -070051const int kMaxResumedUpdateFailures = 10;
Darin Petkov73058b42010-10-06 16:32:19 -070052
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070053// Converts extents to a human-readable string, for use by DumpUpdateProto().
54string ExtentsToString(const RepeatedPtrField<Extent>& extents) {
55 string ret;
56 for (int i = 0; i < extents.size(); i++) {
57 const Extent& extent = extents.Get(i);
58 if (extent.start_block() == kSparseHole) {
59 ret += StringPrintf("{kSparseHole, %" PRIu64 "}, ", extent.num_blocks());
60 } else {
61 ret += StringPrintf("{%" PRIu64 ", %" PRIu64 "}, ",
62 extent.start_block(), extent.num_blocks());
63 }
64 }
65 if (!ret.empty()) {
66 DCHECK_GT(ret.size(), static_cast<size_t>(1));
67 ret.resize(ret.size() - 2);
68 }
69 return ret;
70}
71
72// LOGs a DeltaArchiveManifest object. Useful for debugging.
73void DumpUpdateProto(const DeltaArchiveManifest& manifest) {
74 LOG(INFO) << "Update Proto:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070075 LOG(INFO) << " block_size: " << manifest.block_size();
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070076 for (int i = 0; i < (manifest.install_operations_size() +
77 manifest.kernel_install_operations_size()); i++) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070078 const DeltaArchiveManifest_InstallOperation& op =
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070079 i < manifest.install_operations_size() ?
80 manifest.install_operations(i) :
81 manifest.kernel_install_operations(
82 i - manifest.install_operations_size());
83 if (i == 0)
84 LOG(INFO) << " Rootfs ops:";
85 else if (i == manifest.install_operations_size())
86 LOG(INFO) << " Kernel ops:";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070087 LOG(INFO) << " operation(" << i << ")";
88 LOG(INFO) << " type: "
89 << DeltaArchiveManifest_InstallOperation_Type_Name(op.type());
90 if (op.has_data_offset())
91 LOG(INFO) << " data_offset: " << op.data_offset();
92 if (op.has_data_length())
93 LOG(INFO) << " data_length: " << op.data_length();
94 LOG(INFO) << " src_extents: " << ExtentsToString(op.src_extents());
95 if (op.has_src_length())
96 LOG(INFO) << " src_length: " << op.src_length();
97 LOG(INFO) << " dst_extents: " << ExtentsToString(op.dst_extents());
98 if (op.has_dst_length())
99 LOG(INFO) << " dst_length: " << op.dst_length();
100 }
101}
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700102
103// Opens path for read/write, put the fd into *fd. On success returns true
104// and sets *err to 0. On failure, returns false and sets *err to errno.
105bool OpenFile(const char* path, int* fd, int* err) {
106 if (*fd != -1) {
107 LOG(ERROR) << "Can't open(" << path << "), *fd != -1 (it's " << *fd << ")";
108 *err = EINVAL;
109 return false;
110 }
111 *fd = open(path, O_RDWR, 000);
112 if (*fd < 0) {
113 *err = errno;
114 PLOG(ERROR) << "Unable to open file " << path;
115 return false;
116 }
117 *err = 0;
118 return true;
119}
120
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700121} // namespace {}
122
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800123
124// Computes the ratio of |part| and |total|, scaled to |norm|, using integer
125// arithmetic.
126static uint64_t IntRatio(uint64_t part, uint64_t total, uint64_t norm) {
127 return part * norm / total;
128}
129
130void DeltaPerformer::LogProgress(const char* message_prefix) {
131 // Format operations total count and percentage.
132 string total_operations_str("?");
133 string completed_percentage_str("");
134 if (num_total_operations_) {
135 total_operations_str = StringPrintf("%zu", num_total_operations_);
136 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
137 completed_percentage_str =
138 StringPrintf(" (%llu%%)",
139 IntRatio(next_operation_num_, num_total_operations_,
140 100));
141 }
142
143 // Format download total count and percentage.
144 size_t payload_size = install_plan_->payload_size;
145 string payload_size_str("?");
146 string downloaded_percentage_str("");
147 if (payload_size) {
148 payload_size_str = StringPrintf("%zu", payload_size);
149 // Upcasting to 64-bit to avoid overflow, back to size_t for formatting.
150 downloaded_percentage_str =
151 StringPrintf(" (%llu%%)",
152 IntRatio(total_bytes_received_, payload_size, 100));
153 }
154
155 LOG(INFO) << (message_prefix ? message_prefix : "") << next_operation_num_
156 << "/" << total_operations_str << " operations"
157 << completed_percentage_str << ", " << total_bytes_received_
158 << "/" << payload_size_str << " bytes downloaded"
159 << downloaded_percentage_str << ", overall progress "
160 << overall_progress_ << "%";
161}
162
163void DeltaPerformer::UpdateOverallProgress(bool force_log,
164 const char* message_prefix) {
165 // Compute our download and overall progress.
166 unsigned new_overall_progress = 0;
167 COMPILE_ASSERT(kProgressDownloadWeight + kProgressOperationsWeight == 100,
168 progress_weight_dont_add_up);
169 // Only consider download progress if its total size is known; otherwise
170 // adjust the operations weight to compensate for the absence of download
171 // progress. Also, make sure to cap the download portion at
172 // kProgressDownloadWeight, in case we end up downloading more than we
173 // initially expected (this indicates a problem, but could generally happen).
174 // TODO(garnold) the correction of operations weight when we do not have the
175 // total payload size, as well as the conditional guard below, should both be
176 // eliminated once we ensure that the payload_size in the install plan is
177 // always given and is non-zero. This currently isn't the case during unit
178 // tests (see chromium-os:37969).
179 size_t payload_size = install_plan_->payload_size;
180 unsigned actual_operations_weight = kProgressOperationsWeight;
181 if (payload_size)
182 new_overall_progress += min(
183 static_cast<unsigned>(IntRatio(total_bytes_received_, payload_size,
184 kProgressDownloadWeight)),
185 kProgressDownloadWeight);
186 else
187 actual_operations_weight += kProgressDownloadWeight;
188
189 // Only add completed operations if their total number is known; we definitely
190 // expect an update to have at least one operation, so the expectation is that
191 // this will eventually reach |actual_operations_weight|.
192 if (num_total_operations_)
193 new_overall_progress += IntRatio(next_operation_num_, num_total_operations_,
194 actual_operations_weight);
195
196 // Progress ratio cannot recede, unless our assumptions about the total
197 // payload size, total number of operations, or the monotonicity of progress
198 // is breached.
199 if (new_overall_progress < overall_progress_) {
200 LOG(WARNING) << "progress counter receded from " << overall_progress_
201 << "% down to " << new_overall_progress << "%; this is a bug";
202 force_log = true;
203 }
204 overall_progress_ = new_overall_progress;
205
206 // Update chunk index, log as needed: if forced by called, or we completed a
207 // progress chunk, or a timeout has expired.
208 base::Time curr_time = base::Time::Now();
209 unsigned curr_progress_chunk =
210 overall_progress_ * kProgressLogMaxChunks / 100;
211 if (force_log || curr_progress_chunk > last_progress_chunk_ ||
212 curr_time > forced_progress_log_time_) {
213 forced_progress_log_time_ = curr_time + forced_progress_log_wait_;
214 LogProgress(message_prefix);
215 }
216 last_progress_chunk_ = curr_progress_chunk;
217}
218
219
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700220// Returns true if |op| is idempotent -- i.e., if we can interrupt it and repeat
221// it safely. Returns false otherwise.
222bool DeltaPerformer::IsIdempotentOperation(
223 const DeltaArchiveManifest_InstallOperation& op) {
224 if (op.src_extents_size() == 0) {
225 return true;
226 }
Darin Petkov9fa7ec52010-10-18 11:45:23 -0700227 // When in doubt, it's safe to declare an op non-idempotent. Note that we
228 // could detect other types of idempotent operations here such as a MOVE that
229 // moves blocks onto themselves. However, we rely on the server to not send
230 // such operations at all.
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700231 ExtentRanges src_ranges;
232 src_ranges.AddRepeatedExtents(op.src_extents());
233 const uint64_t block_count = src_ranges.blocks();
234 src_ranges.SubtractRepeatedExtents(op.dst_extents());
235 return block_count == src_ranges.blocks();
236}
237
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700238int DeltaPerformer::Open(const char* path, int flags, mode_t mode) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700239 int err;
240 if (OpenFile(path, &fd_, &err))
241 path_ = path;
242 return -err;
243}
244
245bool DeltaPerformer::OpenKernel(const char* kernel_path) {
246 int err;
247 bool success = OpenFile(kernel_path, &kernel_fd_, &err);
248 if (success)
249 kernel_path_ = kernel_path;
250 return success;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700251}
252
253int DeltaPerformer::Close() {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700254 int err = 0;
255 if (close(kernel_fd_) == -1) {
256 err = errno;
257 PLOG(ERROR) << "Unable to close kernel fd:";
258 }
259 if (close(fd_) == -1) {
260 err = errno;
261 PLOG(ERROR) << "Unable to close rootfs fd:";
262 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700263 LOG_IF(ERROR, !hash_calculator_.Finalize()) << "Unable to finalize the hash.";
Darin Petkov934bb412010-11-18 11:21:35 -0800264 fd_ = -2; // Set to invalid so that calls to Open() will fail.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700265 path_ = "";
Darin Petkov934bb412010-11-18 11:21:35 -0800266 if (!buffer_.empty()) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700267 LOG(INFO) << "Discarding " << buffer_.size() << " unused downloaded bytes";
268 if (err >= 0)
Darin Petkov934bb412010-11-18 11:21:35 -0800269 err = 1;
Darin Petkov934bb412010-11-18 11:21:35 -0800270 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700271 return -err;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700272}
273
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700274namespace {
275
276void LogPartitionInfoHash(const PartitionInfo& info, const string& tag) {
277 string sha256;
278 if (OmahaHashCalculator::Base64Encode(info.hash().data(),
279 info.hash().size(),
280 &sha256)) {
Darin Petkov3aefa862010-12-07 14:45:00 -0800281 LOG(INFO) << "PartitionInfo " << tag << " sha256: " << sha256
282 << " size: " << info.size();
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700283 } else {
284 LOG(ERROR) << "Base64Encode failed for tag: " << tag;
285 }
286}
287
288void LogPartitionInfo(const DeltaArchiveManifest& manifest) {
289 if (manifest.has_old_kernel_info())
290 LogPartitionInfoHash(manifest.old_kernel_info(), "old_kernel_info");
291 if (manifest.has_old_rootfs_info())
292 LogPartitionInfoHash(manifest.old_rootfs_info(), "old_rootfs_info");
293 if (manifest.has_new_kernel_info())
294 LogPartitionInfoHash(manifest.new_kernel_info(), "new_kernel_info");
295 if (manifest.has_new_rootfs_info())
296 LogPartitionInfoHash(manifest.new_rootfs_info(), "new_rootfs_info");
297}
298
299} // namespace {}
300
Jay Srinivasanf4318702012-09-24 11:56:24 -0700301uint64_t DeltaPerformer::GetManifestSizeOffset() {
302 // Manifest size is stored right after the magic string and the version.
303 return strlen(kDeltaMagic) + kDeltaVersionSize;
304}
305
306uint64_t DeltaPerformer::GetManifestOffset() {
307 // Actual manifest begins right after the manifest size field.
308 return GetManifestSizeOffset() + kDeltaManifestSizeSize;
309}
310
311
Darin Petkov9574f7e2011-01-13 10:48:12 -0800312DeltaPerformer::MetadataParseResult DeltaPerformer::ParsePayloadMetadata(
313 const std::vector<char>& payload,
314 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700315 uint64_t* metadata_size,
316 ActionExitCode* error) {
317 *error = kActionCodeSuccess;
318
Jay Srinivasanf4318702012-09-24 11:56:24 -0700319 // manifest_offset is the byte offset where the manifest protobuf begins.
320 const uint64_t manifest_offset = GetManifestOffset();
321 if (payload.size() < manifest_offset) {
322 // Don't have enough bytes to even know the manifest size.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800323 return kMetadataParseInsufficientData;
324 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700325
Jay Srinivasanf4318702012-09-24 11:56:24 -0700326 // Validate the magic string.
Darin Petkov9574f7e2011-01-13 10:48:12 -0800327 if (memcmp(payload.data(), kDeltaMagic, strlen(kDeltaMagic)) != 0) {
328 LOG(ERROR) << "Bad payload format -- invalid delta magic.";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700329 *error = kActionCodeDownloadInvalidMetadataMagicString;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800330 return kMetadataParseError;
331 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700332
333 // TODO(jaysri): Compare the version number and skip unknown manifest
334 // versions. We don't check the version at all today.
335
Jay Srinivasanf4318702012-09-24 11:56:24 -0700336 // Next, parse the manifest size.
337 uint64_t manifest_size;
338 COMPILE_ASSERT(sizeof(manifest_size) == kDeltaManifestSizeSize,
339 manifest_size_size_mismatch);
340 memcpy(&manifest_size,
341 &payload[GetManifestSizeOffset()],
342 kDeltaManifestSizeSize);
343 manifest_size = be64toh(manifest_size); // switch big endian to host
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700344
345 // Now, check if the metasize we computed matches what was passed in
346 // through Omaha Response.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700347 *metadata_size = manifest_offset + manifest_size;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700348
Jay Srinivasanf4318702012-09-24 11:56:24 -0700349 // If the metadata size is present in install plan, check for it immediately
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700350 // even before waiting for that many number of bytes to be downloaded
351 // in the payload. This will prevent any attack which relies on us downloading
Jay Srinivasanf4318702012-09-24 11:56:24 -0700352 // data beyond the expected metadata size.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800353 if (install_plan_->hash_checks_mandatory) {
354 if (install_plan_->metadata_size != *metadata_size) {
355 LOG(ERROR) << "Mandatory metadata size in Omaha response ("
356 << install_plan_->metadata_size << ") is missing/incorrect."
357 << ", Actual = " << *metadata_size;
358 *error = kActionCodeDownloadInvalidMetadataSize;
359 return kMetadataParseError;
360 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700361 }
362
363 // Now that we have validated the metadata size, we should wait for the full
364 // metadata to be read in before we can parse it.
365 if (payload.size() < *metadata_size) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800366 return kMetadataParseInsufficientData;
367 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700368
369 // Log whether we validated the size or simply trusting what's in the payload
Jay Srinivasanf4318702012-09-24 11:56:24 -0700370 // here. This is logged here (after we received the full metadata data) so
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700371 // that we just log once (instead of logging n times) if it takes n
372 // DeltaPerformer::Write calls to download the full manifest.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800373 if (install_plan_->metadata_size == *metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700374 LOG(INFO) << "Manifest size in payload matches expected value from Omaha";
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800375 } else {
376 // For mandatory-cases, we'd have already returned a kMetadataParseError
377 // above. We'll be here only for non-mandatory cases. Just send a UMA stat.
378 LOG(WARNING) << "Ignoring missing/incorrect metadata size ("
379 << install_plan_->metadata_size
380 << ") in Omaha response as validation is not mandatory. "
381 << "Trusting metadata size in payload = " << *metadata_size;
382 SendUmaStat(kActionCodeDownloadInvalidMetadataSize);
383 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700384
Jay Srinivasanf4318702012-09-24 11:56:24 -0700385 // We have the full metadata in |payload|. Verify its integrity
386 // and authenticity based on the information we have in Omaha response.
387 *error = ValidateMetadataSignature(&payload[0], *metadata_size);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700388 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800389 if (install_plan_->hash_checks_mandatory) {
390 LOG(ERROR) << "Mandatory metadata signature validation failed";
391 return kMetadataParseError;
392 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700393
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800394 // For non-mandatory cases, just send a UMA stat.
395 LOG(WARNING) << "Ignoring metadata signature validation failures";
396 SendUmaStat(*error);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700397 *error = kActionCodeSuccess;
398 }
399
Jay Srinivasanf4318702012-09-24 11:56:24 -0700400 // The metadata in |payload| is deemed valid. So, it's now safe to
401 // parse the protobuf.
402 if (!manifest->ParseFromArray(&payload[manifest_offset], manifest_size)) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800403 LOG(ERROR) << "Unable to parse manifest in update file.";
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700404 *error = kActionCodeDownloadManifestParseError;
Darin Petkov9574f7e2011-01-13 10:48:12 -0800405 return kMetadataParseError;
406 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800407 return kMetadataParseSuccess;
408}
409
410
Don Garrette410e0f2011-11-10 15:39:01 -0800411// Wrapper around write. Returns true if all requested bytes
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800412// were written, or false on any error, regardless of progress
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700413// and stores an action exit code in |error|.
414bool DeltaPerformer::Write(const void* bytes, size_t count,
415 ActionExitCode *error) {
416 *error = kActionCodeSuccess;
417
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700418 const char* c_bytes = reinterpret_cast<const char*>(bytes);
419 buffer_.insert(buffer_.end(), c_bytes, c_bytes + count);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800420 system_state_->payload_state()->DownloadProgress(count);
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800421
422 // Update the total byte downloaded count and the progress logs.
423 total_bytes_received_ += count;
424 UpdateOverallProgress(false, "Completed ");
425
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700426 if (!manifest_valid_) {
Darin Petkov9574f7e2011-01-13 10:48:12 -0800427 MetadataParseResult result = ParsePayloadMetadata(buffer_,
428 &manifest_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700429 &manifest_metadata_size_,
430 error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800431 if (result == kMetadataParseError) {
Don Garrette410e0f2011-11-10 15:39:01 -0800432 return false;
Darin Petkov934bb412010-11-18 11:21:35 -0800433 }
Darin Petkov9574f7e2011-01-13 10:48:12 -0800434 if (result == kMetadataParseInsufficientData) {
Don Garrette410e0f2011-11-10 15:39:01 -0800435 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700436 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700437 // Remove protobuf and header info from buffer_, so buffer_ contains
438 // just data blobs
Darin Petkov437adc42010-10-07 13:12:24 -0700439 DiscardBufferHeadBytes(manifest_metadata_size_);
Darin Petkov73058b42010-10-06 16:32:19 -0700440 LOG_IF(WARNING, !prefs_->SetInt64(kPrefsManifestMetadataSize,
Darin Petkov437adc42010-10-07 13:12:24 -0700441 manifest_metadata_size_))
Darin Petkov73058b42010-10-06 16:32:19 -0700442 << "Unable to save the manifest metadata size.";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700443 manifest_valid_ = true;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700444
Andrew de los Reyes89f17be2010-10-22 13:39:09 -0700445 LogPartitionInfo(manifest_);
Darin Petkov9b230572010-10-08 10:20:09 -0700446 if (!PrimeUpdateState()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700447 *error = kActionCodeDownloadStateInitializationError;
Darin Petkov9b230572010-10-08 10:20:09 -0700448 LOG(ERROR) << "Unable to prime the update state.";
Don Garrette410e0f2011-11-10 15:39:01 -0800449 return false;
Darin Petkov9b230572010-10-08 10:20:09 -0700450 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800451
452 num_rootfs_operations_ = manifest_.install_operations_size();
453 num_total_operations_ =
454 num_rootfs_operations_ + manifest_.kernel_install_operations_size();
455 if (next_operation_num_ > 0)
456 UpdateOverallProgress(true, "Resuming after ");
457 LOG(INFO) << "Starting to apply update payload operations";
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700458 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800459
460 while (next_operation_num_ < num_total_operations_) {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700461 // Check if we should cancel the current attempt for any reason.
462 // In this case, *error will have already been populated with the reason
463 // why we're cancelling.
464 if (system_state_->update_attempter()->ShouldCancel(error))
465 return false;
466
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800467 const bool is_kernel_partition =
468 (next_operation_num_ >= num_rootfs_operations_);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700469 const DeltaArchiveManifest_InstallOperation &op =
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800470 is_kernel_partition ?
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700471 manifest_.kernel_install_operations(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800472 next_operation_num_ - num_rootfs_operations_) :
473 manifest_.install_operations(next_operation_num_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700474 if (!CanPerformInstallOperation(op)) {
475 // This means we don't have enough bytes received yet to carry out the
476 // next operation.
477 return true;
478 }
479
Jay Srinivasanf4318702012-09-24 11:56:24 -0700480 // Validate the operation only if the metadata signature is present.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700481 // Otherwise, keep the old behavior. This serves as a knob to disable
482 // the validation logic in case we find some regression after rollout.
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800483 // NOTE: If hash checks are mandatory and if metadata_signature is empty,
484 // we would have already failed in ParsePayloadMetadata method and thus not
485 // even be here. So no need to handle that case again here.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700486 if (!install_plan_->metadata_signature.empty()) {
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700487 // Note: Validate must be called only if CanPerformInstallOperation is
488 // called. Otherwise, we might be failing operations before even if there
489 // isn't sufficient data to compute the proper hash.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800490 *error = ValidateOperationHash(op);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700491 if (*error != kActionCodeSuccess) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800492 if (install_plan_->hash_checks_mandatory) {
493 LOG(ERROR) << "Mandatory operation hash check failed";
494 return false;
495 }
Jay Srinivasanf0572052012-10-23 18:12:56 -0700496
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800497 // For non-mandatory cases, just send a UMA stat.
498 LOG(WARNING) << "Ignoring operation validation errors";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700499 SendUmaStat(*error);
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800500 *error = kActionCodeSuccess;
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700501 }
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700502 }
503
Darin Petkov45580e42010-10-08 14:02:40 -0700504 // Makes sure we unblock exit when this operation completes.
Darin Petkov9c0baf82010-10-07 13:44:48 -0700505 ScopedTerminatorExitUnblocker exit_unblocker =
506 ScopedTerminatorExitUnblocker(); // Avoids a compiler unused var bug.
Andrew de los Reyesbef0c7d2010-08-20 10:20:10 -0700507 // Log every thousandth operation, and also the first and last ones
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700508 if (op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
509 op.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700510 if (!PerformReplaceOperation(op, is_kernel_partition)) {
511 LOG(ERROR) << "Failed to perform replace operation "
512 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700513 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800514 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700515 }
516 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700517 if (!PerformMoveOperation(op, is_kernel_partition)) {
518 LOG(ERROR) << "Failed to perform move operation "
519 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700520 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800521 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700522 }
523 } else if (op.type() == DeltaArchiveManifest_InstallOperation_Type_BSDIFF) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700524 if (!PerformBsdiffOperation(op, is_kernel_partition)) {
525 LOG(ERROR) << "Failed to perform bsdiff operation "
526 << next_operation_num_;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700527 *error = kActionCodeDownloadOperationExecutionError;
Don Garrette410e0f2011-11-10 15:39:01 -0800528 return false;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700529 }
530 }
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800531
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700532 next_operation_num_++;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800533 UpdateOverallProgress(false, "Completed ");
Darin Petkov73058b42010-10-06 16:32:19 -0700534 CheckpointUpdateProgress();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700535 }
Don Garrette410e0f2011-11-10 15:39:01 -0800536 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700537}
538
539bool DeltaPerformer::CanPerformInstallOperation(
540 const chromeos_update_engine::DeltaArchiveManifest_InstallOperation&
541 operation) {
542 // Move operations don't require any data blob, so they can always
543 // be performed
544 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_MOVE)
545 return true;
546
547 // See if we have the entire data blob in the buffer
548 if (operation.data_offset() < buffer_offset_) {
549 LOG(ERROR) << "we threw away data it seems?";
550 return false;
551 }
Darin Petkovd7061ab2010-10-06 14:37:09 -0700552
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700553 return (operation.data_offset() + operation.data_length()) <=
554 (buffer_offset_ + buffer_.size());
555}
556
557bool DeltaPerformer::PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700558 const DeltaArchiveManifest_InstallOperation& operation,
559 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700560 CHECK(operation.type() == \
561 DeltaArchiveManifest_InstallOperation_Type_REPLACE || \
562 operation.type() == \
563 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ);
564
565 // Since we delete data off the beginning of the buffer as we use it,
566 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700567 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
568 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700569
Darin Petkov437adc42010-10-07 13:12:24 -0700570 // Extract the signature message if it's in this operation.
571 ExtractSignatureMessage(operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700572
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700573 DirectExtentWriter direct_writer;
574 ZeroPadExtentWriter zero_pad_writer(&direct_writer);
575 scoped_ptr<BzipExtentWriter> bzip_writer;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700576
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700577 // Since bzip decompression is optional, we have a variable writer that will
578 // point to one of the ExtentWriter objects above.
579 ExtentWriter* writer = NULL;
580 if (operation.type() == DeltaArchiveManifest_InstallOperation_Type_REPLACE) {
581 writer = &zero_pad_writer;
582 } else if (operation.type() ==
583 DeltaArchiveManifest_InstallOperation_Type_REPLACE_BZ) {
584 bzip_writer.reset(new BzipExtentWriter(&zero_pad_writer));
585 writer = bzip_writer.get();
586 } else {
587 NOTREACHED();
588 }
589
590 // Create a vector of extents to pass to the ExtentWriter.
591 vector<Extent> extents;
592 for (int i = 0; i < operation.dst_extents_size(); i++) {
593 extents.push_back(operation.dst_extents(i));
594 }
595
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700596 int fd = is_kernel_partition ? kernel_fd_ : fd_;
597
598 TEST_AND_RETURN_FALSE(writer->Init(fd, extents, block_size_));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700599 TEST_AND_RETURN_FALSE(writer->Write(&buffer_[0], operation.data_length()));
600 TEST_AND_RETURN_FALSE(writer->End());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700601
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700602 // Update buffer
603 buffer_offset_ += operation.data_length();
Darin Petkov437adc42010-10-07 13:12:24 -0700604 DiscardBufferHeadBytes(operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700605 return true;
606}
607
608bool DeltaPerformer::PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700609 const DeltaArchiveManifest_InstallOperation& operation,
610 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700611 // Calculate buffer size. Note, this function doesn't do a sliding
612 // window to copy in case the source and destination blocks overlap.
613 // If we wanted to do a sliding window, we could program the server
614 // to generate deltas that effectively did a sliding window.
615
616 uint64_t blocks_to_read = 0;
617 for (int i = 0; i < operation.src_extents_size(); i++)
618 blocks_to_read += operation.src_extents(i).num_blocks();
619
620 uint64_t blocks_to_write = 0;
621 for (int i = 0; i < operation.dst_extents_size(); i++)
622 blocks_to_write += operation.dst_extents(i).num_blocks();
623
624 DCHECK_EQ(blocks_to_write, blocks_to_read);
625 vector<char> buf(blocks_to_write * block_size_);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700626
627 int fd = is_kernel_partition ? kernel_fd_ : fd_;
628
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700629 // Read in bytes.
630 ssize_t bytes_read = 0;
631 for (int i = 0; i < operation.src_extents_size(); i++) {
632 ssize_t bytes_read_this_iteration = 0;
633 const Extent& extent = operation.src_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700634 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700635 &buf[bytes_read],
636 extent.num_blocks() * block_size_,
637 extent.start_block() * block_size_,
638 &bytes_read_this_iteration));
639 TEST_AND_RETURN_FALSE(
640 bytes_read_this_iteration ==
641 static_cast<ssize_t>(extent.num_blocks() * block_size_));
642 bytes_read += bytes_read_this_iteration;
643 }
644
Darin Petkov45580e42010-10-08 14:02:40 -0700645 // If this is a non-idempotent operation, request a delayed exit and clear the
646 // update state in case the operation gets interrupted. Do this as late as
647 // possible.
648 if (!IsIdempotentOperation(operation)) {
649 Terminator::set_exit_blocked(true);
650 ResetUpdateProgress(prefs_, true);
651 }
652
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700653 // Write bytes out.
654 ssize_t bytes_written = 0;
655 for (int i = 0; i < operation.dst_extents_size(); i++) {
656 const Extent& extent = operation.dst_extents(i);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700657 TEST_AND_RETURN_FALSE(utils::PWriteAll(fd,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700658 &buf[bytes_written],
659 extent.num_blocks() * block_size_,
660 extent.start_block() * block_size_));
661 bytes_written += extent.num_blocks() * block_size_;
662 }
663 DCHECK_EQ(bytes_written, bytes_read);
664 DCHECK_EQ(bytes_written, static_cast<ssize_t>(buf.size()));
665 return true;
666}
667
668bool DeltaPerformer::ExtentsToBsdiffPositionsString(
669 const RepeatedPtrField<Extent>& extents,
670 uint64_t block_size,
671 uint64_t full_length,
672 string* positions_string) {
673 string ret;
674 uint64_t length = 0;
675 for (int i = 0; i < extents.size(); i++) {
676 Extent extent = extents.Get(i);
677 int64_t start = extent.start_block();
678 uint64_t this_length = min(full_length - length,
679 extent.num_blocks() * block_size);
680 if (start == static_cast<int64_t>(kSparseHole))
681 start = -1;
682 else
683 start *= block_size;
684 ret += StringPrintf("%" PRIi64 ":%" PRIu64 ",", start, this_length);
685 length += this_length;
686 }
687 TEST_AND_RETURN_FALSE(length == full_length);
688 if (!ret.empty())
689 ret.resize(ret.size() - 1); // Strip trailing comma off
690 *positions_string = ret;
691 return true;
692}
693
694bool DeltaPerformer::PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700695 const DeltaArchiveManifest_InstallOperation& operation,
696 bool is_kernel_partition) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700697 // Since we delete data off the beginning of the buffer as we use it,
698 // the data we need should be exactly at the beginning of the buffer.
Darin Petkov9b230572010-10-08 10:20:09 -0700699 TEST_AND_RETURN_FALSE(buffer_offset_ == operation.data_offset());
700 TEST_AND_RETURN_FALSE(buffer_.size() >= operation.data_length());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700701
702 string input_positions;
703 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.src_extents(),
704 block_size_,
705 operation.src_length(),
706 &input_positions));
707 string output_positions;
708 TEST_AND_RETURN_FALSE(ExtentsToBsdiffPositionsString(operation.dst_extents(),
709 block_size_,
710 operation.dst_length(),
711 &output_positions));
712
713 string temp_filename;
714 TEST_AND_RETURN_FALSE(utils::MakeTempFile("/tmp/au_patch.XXXXXX",
715 &temp_filename,
716 NULL));
717 ScopedPathUnlinker path_unlinker(temp_filename);
718 {
719 int fd = open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
720 ScopedFdCloser fd_closer(&fd);
721 TEST_AND_RETURN_FALSE(
722 utils::WriteAll(fd, &buffer_[0], operation.data_length()));
723 }
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700724
Darin Petkov7f2ec752013-04-03 14:45:19 +0200725 // Update the buffer to release the patch data memory as soon as the patch
726 // file is written out.
727 buffer_offset_ += operation.data_length();
728 DiscardBufferHeadBytes(operation.data_length());
729
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700730 int fd = is_kernel_partition ? kernel_fd_ : fd_;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700731 const string& path = StringPrintf("/dev/fd/%d", fd);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700732
Darin Petkov45580e42010-10-08 14:02:40 -0700733 // If this is a non-idempotent operation, request a delayed exit and clear the
734 // update state in case the operation gets interrupted. Do this as late as
735 // possible.
736 if (!IsIdempotentOperation(operation)) {
737 Terminator::set_exit_blocked(true);
738 ResetUpdateProgress(prefs_, true);
739 }
740
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700741 vector<string> cmd;
742 cmd.push_back(kBspatchPath);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700743 cmd.push_back(path);
744 cmd.push_back(path);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700745 cmd.push_back(temp_filename);
746 cmd.push_back(input_positions);
747 cmd.push_back(output_positions);
748 int return_code = 0;
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700749 TEST_AND_RETURN_FALSE(
750 Subprocess::SynchronousExecFlags(cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700751 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
Andrew de los Reyes5a232832010-10-12 16:20:54 -0700752 &return_code,
Darin Petkov85d02b72011-05-17 13:25:51 -0700753 NULL));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700754 TEST_AND_RETURN_FALSE(return_code == 0);
755
756 if (operation.dst_length() % block_size_) {
757 // Zero out rest of final block.
758 // TODO(adlr): build this into bspatch; it's more efficient that way.
759 const Extent& last_extent =
760 operation.dst_extents(operation.dst_extents_size() - 1);
761 const uint64_t end_byte =
762 (last_extent.start_block() + last_extent.num_blocks()) * block_size_;
763 const uint64_t begin_byte =
764 end_byte - (block_size_ - operation.dst_length() % block_size_);
765 vector<char> zeros(end_byte - begin_byte);
766 TEST_AND_RETURN_FALSE(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700767 utils::PWriteAll(fd, &zeros[0], end_byte - begin_byte, begin_byte));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700768 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700769 return true;
770}
771
Darin Petkovd7061ab2010-10-06 14:37:09 -0700772bool DeltaPerformer::ExtractSignatureMessage(
773 const DeltaArchiveManifest_InstallOperation& operation) {
774 if (operation.type() != DeltaArchiveManifest_InstallOperation_Type_REPLACE ||
775 !manifest_.has_signatures_offset() ||
776 manifest_.signatures_offset() != operation.data_offset()) {
777 return false;
778 }
779 TEST_AND_RETURN_FALSE(manifest_.has_signatures_size() &&
780 manifest_.signatures_size() == operation.data_length());
781 TEST_AND_RETURN_FALSE(signatures_message_data_.empty());
782 TEST_AND_RETURN_FALSE(buffer_offset_ == manifest_.signatures_offset());
783 TEST_AND_RETURN_FALSE(buffer_.size() >= manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700784 signatures_message_data_.assign(
Darin Petkovd7061ab2010-10-06 14:37:09 -0700785 buffer_.begin(),
786 buffer_.begin() + manifest_.signatures_size());
Darin Petkov4f0a07b2011-05-25 16:47:20 -0700787
788 // Save the signature blob because if the update is interrupted after the
789 // download phase we don't go through this path anymore. Some alternatives to
790 // consider:
791 //
792 // 1. On resume, re-download the signature blob from the server and re-verify
793 // it.
794 //
795 // 2. Verify the signature as soon as it's received and don't checkpoint the
796 // blob and the signed sha-256 context.
797 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignatureBlob,
798 string(&signatures_message_data_[0],
799 signatures_message_data_.size())))
800 << "Unable to store the signature blob.";
Darin Petkov437adc42010-10-07 13:12:24 -0700801 // The hash of all data consumed so far should be verified against the signed
802 // hash.
803 signed_hash_context_ = hash_calculator_.GetContext();
804 LOG_IF(WARNING, !prefs_->SetString(kPrefsUpdateStateSignedSHA256Context,
805 signed_hash_context_))
806 << "Unable to store the signed hash context.";
Darin Petkovd7061ab2010-10-06 14:37:09 -0700807 LOG(INFO) << "Extracted signature data of size "
808 << manifest_.signatures_size() << " at "
809 << manifest_.signatures_offset();
810 return true;
811}
812
Jay Srinivasanf4318702012-09-24 11:56:24 -0700813ActionExitCode DeltaPerformer::ValidateMetadataSignature(
814 const char* metadata, uint64_t metadata_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700815
Jay Srinivasanf4318702012-09-24 11:56:24 -0700816 if (install_plan_->metadata_signature.empty()) {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800817 if (install_plan_->hash_checks_mandatory) {
818 LOG(ERROR) << "Missing mandatory metadata signature in Omaha response";
819 return kActionCodeDownloadMetadataSignatureMissingError;
820 }
821
822 // For non-mandatory cases, just send a UMA stat.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700823 LOG(WARNING) << "Cannot validate metadata as the signature is empty";
Jay Srinivasanedce2832012-10-24 18:57:47 -0700824 SendUmaStat(kActionCodeDownloadMetadataSignatureMissingError);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700825 return kActionCodeSuccess;
826 }
827
828 // Convert base64-encoded signature to raw bytes.
Jay Srinivasanf4318702012-09-24 11:56:24 -0700829 vector<char> metadata_signature;
830 if (!OmahaHashCalculator::Base64Decode(install_plan_->metadata_signature,
831 &metadata_signature)) {
832 LOG(ERROR) << "Unable to decode base64 metadata signature: "
833 << install_plan_->metadata_signature;
834 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700835 }
836
Jay Srinivasanf4318702012-09-24 11:56:24 -0700837 vector<char> expected_metadata_hash;
838 if (!PayloadSigner::GetRawHashFromSignature(metadata_signature,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700839 public_key_path_,
Jay Srinivasanf4318702012-09-24 11:56:24 -0700840 &expected_metadata_hash)) {
841 LOG(ERROR) << "Unable to compute expected hash from metadata signature";
842 return kActionCodeDownloadMetadataSignatureError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700843 }
844
Jay Srinivasanf4318702012-09-24 11:56:24 -0700845 OmahaHashCalculator metadata_hasher;
846 metadata_hasher.Update(metadata, metadata_size);
847 if (!metadata_hasher.Finalize()) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700848 LOG(ERROR) << "Unable to compute actual hash of manifest";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700849 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700850 }
851
Jay Srinivasanf4318702012-09-24 11:56:24 -0700852 vector<char> calculated_metadata_hash = metadata_hasher.raw_hash();
853 PayloadSigner::PadRSA2048SHA256Hash(&calculated_metadata_hash);
854 if (calculated_metadata_hash.empty()) {
855 LOG(ERROR) << "Computed actual hash of metadata is empty.";
856 return kActionCodeDownloadMetadataSignatureVerificationError;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700857 }
858
Jay Srinivasanf4318702012-09-24 11:56:24 -0700859 if (calculated_metadata_hash != expected_metadata_hash) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700860 LOG(ERROR) << "Manifest hash verification failed. Expected hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700861 utils::HexDumpVector(expected_metadata_hash);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700862 LOG(ERROR) << "Calculated hash = ";
Jay Srinivasanf4318702012-09-24 11:56:24 -0700863 utils::HexDumpVector(calculated_metadata_hash);
864 return kActionCodeDownloadMetadataSignatureMismatch;
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700865 }
866
867 LOG(INFO) << "Manifest signature matches expected value in Omaha response";
868 return kActionCodeSuccess;
869}
870
871ActionExitCode DeltaPerformer::ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800872 const DeltaArchiveManifest_InstallOperation& operation) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700873
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700874 if (!operation.data_sha256_hash().size()) {
875 if (!operation.data_length()) {
876 // Operations that do not have any data blob won't have any operation hash
877 // either. So, these operations are always considered validated since the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700878 // metadata that contains all the non-data-blob portions of the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800879 // has already been validated. This is true for both HTTP and HTTPS cases.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700880 return kActionCodeSuccess;
881 }
882
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800883 // No hash is present for an operation that has data blobs. This shouldn't
884 // happen normally for any client that has this code, because the
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700885 // corresponding update should have been produced with the operation
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800886 // hashes. So if it happens it means either we've turned operation hash
887 // generation off in DeltaDiffGenerator or it's a regression of some sort.
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700888 // One caveat though: The last operation is a dummy signature operation
889 // that doesn't have a hash at the time the manifest is created. So we
890 // should not complaint about that operation. This operation can be
891 // recognized by the fact that it's offset is mentioned in the manifest.
892 if (manifest_.signatures_offset() &&
893 manifest_.signatures_offset() == operation.data_offset()) {
894 LOG(INFO) << "Skipping hash verification for signature operation "
895 << next_operation_num_ + 1;
896 } else {
Jay Srinivasan738fdf32012-12-07 17:40:54 -0800897 if (install_plan_->hash_checks_mandatory) {
898 LOG(ERROR) << "Missing mandatory operation hash for operation "
899 << next_operation_num_ + 1;
900 return kActionCodeDownloadOperationHashMissingError;
901 }
902
903 // For non-mandatory cases, just send a UMA stat.
904 LOG(WARNING) << "Cannot validate operation " << next_operation_num_ + 1
905 << " as there's no operation hash in manifest";
906 SendUmaStat(kActionCodeDownloadOperationHashMissingError);
Jay Srinivasan00f76b62012-09-17 18:48:36 -0700907 }
908 return kActionCodeSuccess;
909 }
910
911 vector<char> expected_op_hash;
912 expected_op_hash.assign(operation.data_sha256_hash().data(),
913 (operation.data_sha256_hash().data() +
914 operation.data_sha256_hash().size()));
915
916 OmahaHashCalculator operation_hasher;
917 operation_hasher.Update(&buffer_[0], operation.data_length());
918 if (!operation_hasher.Finalize()) {
919 LOG(ERROR) << "Unable to compute actual hash of operation "
920 << next_operation_num_;
921 return kActionCodeDownloadOperationHashVerificationError;
922 }
923
924 vector<char> calculated_op_hash = operation_hasher.raw_hash();
925 if (calculated_op_hash != expected_op_hash) {
926 LOG(ERROR) << "Hash verification failed for operation "
927 << next_operation_num_ << ". Expected hash = ";
928 utils::HexDumpVector(expected_op_hash);
929 LOG(ERROR) << "Calculated hash over " << operation.data_length()
930 << " bytes at offset: " << operation.data_offset() << " = ";
931 utils::HexDumpVector(calculated_op_hash);
932 return kActionCodeDownloadOperationHashMismatch;
933 }
934
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700935 return kActionCodeSuccess;
936}
937
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700938#define TEST_AND_RETURN_VAL(_retval, _condition) \
939 do { \
940 if (!(_condition)) { \
941 LOG(ERROR) << "VerifyPayload failure: " << #_condition; \
942 return _retval; \
943 } \
944 } while (0);
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700945
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700946ActionExitCode DeltaPerformer::VerifyPayload(
Darin Petkov437adc42010-10-07 13:12:24 -0700947 const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700948 const uint64_t update_check_response_size) {
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700949 LOG(INFO) << "Verifying delta payload using public key: " << public_key_path_;
Darin Petkov437adc42010-10-07 13:12:24 -0700950
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700951 // Verifies the download size.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700952 TEST_AND_RETURN_VAL(kActionCodePayloadSizeMismatchError,
Jay Srinivasan0d8fb402012-05-07 19:19:38 -0700953 update_check_response_size ==
954 manifest_metadata_size_ + buffer_offset_);
955
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700956 // Verifies the payload hash.
957 const string& payload_hash_data = hash_calculator_.hash();
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700958 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadVerificationError,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700959 !payload_hash_data.empty());
960 TEST_AND_RETURN_VAL(kActionCodePayloadHashMismatchError,
961 payload_hash_data == update_check_response_hash);
Darin Petkov437adc42010-10-07 13:12:24 -0700962
Darin Petkov437adc42010-10-07 13:12:24 -0700963 // Verifies the signed payload hash.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700964 if (!utils::FileExists(public_key_path_.c_str())) {
Darin Petkov437adc42010-10-07 13:12:24 -0700965 LOG(WARNING) << "Not verifying signed delta payload -- missing public key.";
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700966 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700967 }
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700968 TEST_AND_RETURN_VAL(kActionCodeSignedDeltaPayloadExpectedError,
969 !signatures_message_data_.empty());
Darin Petkovd7061ab2010-10-06 14:37:09 -0700970 vector<char> signed_hash_data;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700971 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
972 PayloadSigner::VerifySignature(
973 signatures_message_data_,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700974 public_key_path_,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700975 &signed_hash_data));
Darin Petkov437adc42010-10-07 13:12:24 -0700976 OmahaHashCalculator signed_hasher;
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700977 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
978 signed_hasher.SetContext(signed_hash_context_));
979 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
980 signed_hasher.Finalize());
Andrew de los Reyesbdfaaf02011-03-30 10:35:12 -0700981 vector<char> hash_data = signed_hasher.raw_hash();
982 PayloadSigner::PadRSA2048SHA256Hash(&hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700983 TEST_AND_RETURN_VAL(kActionCodeDownloadPayloadPubKeyVerificationError,
984 !hash_data.empty());
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700985 if (hash_data != signed_hash_data) {
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700986 LOG(ERROR) << "Public key verification failed, thus update failed. "
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700987 "Attached Signature:";
988 utils::HexDumpVector(signed_hash_data);
989 LOG(ERROR) << "Computed Signature:";
990 utils::HexDumpVector(hash_data);
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700991 return kActionCodeDownloadPayloadPubKeyVerificationError;
Andrew de los Reyesfb830ba2011-04-04 11:42:43 -0700992 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800993
994 // At this point, we are guaranteed to have downloaded a full payload, i.e
995 // the one whose size matches the size mentioned in Omaha response. If any
996 // errors happen after this, it's likely a problem with the payload itself or
997 // the state of the system and not a problem with the URL or network. So,
Jay Srinivasan08262882012-12-28 19:29:43 -0800998 // indicate that to the payload state so that AU can backoff appropriately.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800999 system_state_->payload_state()->DownloadComplete();
1000
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -07001001 return kActionCodeSuccess;
Darin Petkovd7061ab2010-10-06 14:37:09 -07001002}
1003
Darin Petkov3aefa862010-12-07 14:45:00 -08001004bool DeltaPerformer::GetNewPartitionInfo(uint64_t* kernel_size,
1005 vector<char>* kernel_hash,
1006 uint64_t* rootfs_size,
1007 vector<char>* rootfs_hash) {
Darin Petkov2dd01092010-10-08 15:43:05 -07001008 TEST_AND_RETURN_FALSE(manifest_valid_ &&
1009 manifest_.has_new_kernel_info() &&
1010 manifest_.has_new_rootfs_info());
Darin Petkov3aefa862010-12-07 14:45:00 -08001011 *kernel_size = manifest_.new_kernel_info().size();
1012 *rootfs_size = manifest_.new_rootfs_info().size();
1013 vector<char> new_kernel_hash(manifest_.new_kernel_info().hash().begin(),
1014 manifest_.new_kernel_info().hash().end());
1015 vector<char> new_rootfs_hash(manifest_.new_rootfs_info().hash().begin(),
1016 manifest_.new_rootfs_info().hash().end());
1017 kernel_hash->swap(new_kernel_hash);
1018 rootfs_hash->swap(new_rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -07001019 return true;
1020}
1021
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001022namespace {
1023void LogVerifyError(bool is_kern,
1024 const string& local_hash,
1025 const string& expected_hash) {
1026 const char* type = is_kern ? "kernel" : "rootfs";
1027 LOG(ERROR) << "This is a server-side error due to "
1028 << "mismatched delta update image!";
1029 LOG(ERROR) << "The delta I've been given contains a " << type << " delta "
1030 << "update that must be applied over a " << type << " with "
1031 << "a specific checksum, but the " << type << " we're starting "
1032 << "with doesn't have that checksum! This means that "
1033 << "the delta I've been given doesn't match my existing "
1034 << "system. The " << type << " partition I have has hash: "
1035 << local_hash << " but the update expected me to have "
1036 << expected_hash << " .";
1037 if (is_kern) {
1038 LOG(INFO) << "To get the checksum of a kernel partition on a "
1039 << "booted machine, run this command (change /dev/sda2 "
1040 << "as needed): dd if=/dev/sda2 bs=1M 2>/dev/null | "
1041 << "openssl dgst -sha256 -binary | openssl base64";
1042 } else {
1043 LOG(INFO) << "To get the checksum of a rootfs partition on a "
1044 << "booted machine, run this command (change /dev/sda3 "
1045 << "as needed): dd if=/dev/sda3 bs=1M count=$(( "
1046 << "$(dumpe2fs /dev/sda3 2>/dev/null | grep 'Block count' "
1047 << "| sed 's/[^0-9]*//') / 256 )) | "
1048 << "openssl dgst -sha256 -binary | openssl base64";
1049 }
1050 LOG(INFO) << "To get the checksum of partitions in a bin file, "
1051 << "run: .../src/scripts/sha256_partitions.sh .../file.bin";
1052}
1053
1054string StringForHashBytes(const void* bytes, size_t size) {
1055 string ret;
1056 if (!OmahaHashCalculator::Base64Encode(bytes, size, &ret)) {
1057 ret = "<unknown>";
1058 }
1059 return ret;
1060}
1061} // namespace
1062
Darin Petkov698d0412010-10-13 10:59:44 -07001063bool DeltaPerformer::VerifySourcePartitions() {
1064 LOG(INFO) << "Verifying source partitions.";
1065 CHECK(manifest_valid_);
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001066 CHECK(install_plan_);
Darin Petkov698d0412010-10-13 10:59:44 -07001067 if (manifest_.has_old_kernel_info()) {
1068 const PartitionInfo& info = manifest_.old_kernel_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001069 bool valid =
1070 !install_plan_->kernel_hash.empty() &&
1071 install_plan_->kernel_hash.size() == info.hash().size() &&
1072 memcmp(install_plan_->kernel_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001073 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001074 install_plan_->kernel_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001075 if (!valid) {
1076 LogVerifyError(true,
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001077 StringForHashBytes(install_plan_->kernel_hash.data(),
1078 install_plan_->kernel_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001079 StringForHashBytes(info.hash().data(),
1080 info.hash().size()));
1081 }
1082 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001083 }
1084 if (manifest_.has_old_rootfs_info()) {
1085 const PartitionInfo& info = manifest_.old_rootfs_info();
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001086 bool valid =
1087 !install_plan_->rootfs_hash.empty() &&
1088 install_plan_->rootfs_hash.size() == info.hash().size() &&
1089 memcmp(install_plan_->rootfs_hash.data(),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001090 info.hash().data(),
Jay Srinivasan51dcf262012-09-13 17:24:32 -07001091 install_plan_->rootfs_hash.size()) == 0;
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001092 if (!valid) {
1093 LogVerifyError(false,
Chris Sosa670d6802013-03-29 14:17:45 -07001094 StringForHashBytes(install_plan_->rootfs_hash.data(),
1095 install_plan_->rootfs_hash.size()),
Andrew de los Reyes100bb7d2011-08-09 17:35:07 -07001096 StringForHashBytes(info.hash().data(),
1097 info.hash().size()));
1098 }
1099 TEST_AND_RETURN_FALSE(valid);
Darin Petkov698d0412010-10-13 10:59:44 -07001100 }
1101 return true;
1102}
1103
Darin Petkov437adc42010-10-07 13:12:24 -07001104void DeltaPerformer::DiscardBufferHeadBytes(size_t count) {
1105 hash_calculator_.Update(&buffer_[0], count);
Darin Petkov7f2ec752013-04-03 14:45:19 +02001106 // Copy the remainder data into a temporary vector first to ensure that any
1107 // unused memory in the updated |buffer_| will be released.
1108 vector<char> temp(buffer_.begin() + count, buffer_.end());
1109 buffer_.swap(temp);
Darin Petkovd7061ab2010-10-06 14:37:09 -07001110}
1111
Darin Petkov0406e402010-10-06 21:33:11 -07001112bool DeltaPerformer::CanResumeUpdate(PrefsInterface* prefs,
1113 string update_check_response_hash) {
1114 int64_t next_operation = kUpdateStateOperationInvalid;
1115 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextOperation,
1116 &next_operation) &&
1117 next_operation != kUpdateStateOperationInvalid &&
1118 next_operation > 0);
1119
1120 string interrupted_hash;
1121 TEST_AND_RETURN_FALSE(prefs->GetString(kPrefsUpdateCheckResponseHash,
1122 &interrupted_hash) &&
1123 !interrupted_hash.empty() &&
1124 interrupted_hash == update_check_response_hash);
1125
Darin Petkov61426142010-10-08 11:04:55 -07001126 int64_t resumed_update_failures;
1127 TEST_AND_RETURN_FALSE(!prefs->GetInt64(kPrefsResumedUpdateFailures,
1128 &resumed_update_failures) ||
1129 resumed_update_failures <= kMaxResumedUpdateFailures);
1130
Darin Petkov0406e402010-10-06 21:33:11 -07001131 // Sanity check the rest.
1132 int64_t next_data_offset = -1;
1133 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsUpdateStateNextDataOffset,
1134 &next_data_offset) &&
1135 next_data_offset >= 0);
1136
Darin Petkov437adc42010-10-07 13:12:24 -07001137 string sha256_context;
Darin Petkov0406e402010-10-06 21:33:11 -07001138 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001139 prefs->GetString(kPrefsUpdateStateSHA256Context, &sha256_context) &&
1140 !sha256_context.empty());
Darin Petkov0406e402010-10-06 21:33:11 -07001141
1142 int64_t manifest_metadata_size = 0;
1143 TEST_AND_RETURN_FALSE(prefs->GetInt64(kPrefsManifestMetadataSize,
1144 &manifest_metadata_size) &&
1145 manifest_metadata_size > 0);
1146
1147 return true;
1148}
1149
Darin Petkov9b230572010-10-08 10:20:09 -07001150bool DeltaPerformer::ResetUpdateProgress(PrefsInterface* prefs, bool quick) {
Darin Petkov0406e402010-10-06 21:33:11 -07001151 TEST_AND_RETURN_FALSE(prefs->SetInt64(kPrefsUpdateStateNextOperation,
1152 kUpdateStateOperationInvalid));
Darin Petkov9b230572010-10-08 10:20:09 -07001153 if (!quick) {
1154 prefs->SetString(kPrefsUpdateCheckResponseHash, "");
1155 prefs->SetInt64(kPrefsUpdateStateNextDataOffset, -1);
1156 prefs->SetString(kPrefsUpdateStateSHA256Context, "");
1157 prefs->SetString(kPrefsUpdateStateSignedSHA256Context, "");
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001158 prefs->SetString(kPrefsUpdateStateSignatureBlob, "");
Darin Petkov9b230572010-10-08 10:20:09 -07001159 prefs->SetInt64(kPrefsManifestMetadataSize, -1);
Darin Petkov61426142010-10-08 11:04:55 -07001160 prefs->SetInt64(kPrefsResumedUpdateFailures, 0);
Darin Petkov9b230572010-10-08 10:20:09 -07001161 }
Darin Petkov73058b42010-10-06 16:32:19 -07001162 return true;
1163}
1164
1165bool DeltaPerformer::CheckpointUpdateProgress() {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001166 Terminator::set_exit_blocked(true);
Darin Petkov0406e402010-10-06 21:33:11 -07001167 if (last_updated_buffer_offset_ != buffer_offset_) {
Darin Petkov9c0baf82010-10-07 13:44:48 -07001168 // Resets the progress in case we die in the middle of the state update.
Darin Petkov9b230572010-10-08 10:20:09 -07001169 ResetUpdateProgress(prefs_, true);
Darin Petkov0406e402010-10-06 21:33:11 -07001170 TEST_AND_RETURN_FALSE(
Darin Petkov437adc42010-10-07 13:12:24 -07001171 prefs_->SetString(kPrefsUpdateStateSHA256Context,
Darin Petkov0406e402010-10-06 21:33:11 -07001172 hash_calculator_.GetContext()));
1173 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextDataOffset,
1174 buffer_offset_));
1175 last_updated_buffer_offset_ = buffer_offset_;
1176 }
Darin Petkov73058b42010-10-06 16:32:19 -07001177 TEST_AND_RETURN_FALSE(prefs_->SetInt64(kPrefsUpdateStateNextOperation,
1178 next_operation_num_));
1179 return true;
1180}
1181
Darin Petkov9b230572010-10-08 10:20:09 -07001182bool DeltaPerformer::PrimeUpdateState() {
1183 CHECK(manifest_valid_);
1184 block_size_ = manifest_.block_size();
1185
1186 int64_t next_operation = kUpdateStateOperationInvalid;
1187 if (!prefs_->GetInt64(kPrefsUpdateStateNextOperation, &next_operation) ||
1188 next_operation == kUpdateStateOperationInvalid ||
1189 next_operation <= 0) {
1190 // Initiating a new update, no more state needs to be initialized.
Darin Petkov698d0412010-10-13 10:59:44 -07001191 TEST_AND_RETURN_FALSE(VerifySourcePartitions());
Darin Petkov9b230572010-10-08 10:20:09 -07001192 return true;
1193 }
1194 next_operation_num_ = next_operation;
1195
1196 // Resuming an update -- load the rest of the update state.
1197 int64_t next_data_offset = -1;
1198 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsUpdateStateNextDataOffset,
1199 &next_data_offset) &&
1200 next_data_offset >= 0);
1201 buffer_offset_ = next_data_offset;
1202
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001203 // The signed hash context and the signature blob may be empty if the
1204 // interrupted update didn't reach the signature.
Darin Petkov9b230572010-10-08 10:20:09 -07001205 prefs_->GetString(kPrefsUpdateStateSignedSHA256Context,
1206 &signed_hash_context_);
Darin Petkov4f0a07b2011-05-25 16:47:20 -07001207 string signature_blob;
1208 if (prefs_->GetString(kPrefsUpdateStateSignatureBlob, &signature_blob)) {
1209 signatures_message_data_.assign(signature_blob.begin(),
1210 signature_blob.end());
1211 }
Darin Petkov9b230572010-10-08 10:20:09 -07001212
1213 string hash_context;
1214 TEST_AND_RETURN_FALSE(prefs_->GetString(kPrefsUpdateStateSHA256Context,
1215 &hash_context) &&
1216 hash_calculator_.SetContext(hash_context));
1217
1218 int64_t manifest_metadata_size = 0;
1219 TEST_AND_RETURN_FALSE(prefs_->GetInt64(kPrefsManifestMetadataSize,
1220 &manifest_metadata_size) &&
1221 manifest_metadata_size > 0);
1222 manifest_metadata_size_ = manifest_metadata_size;
1223
Gilad Arnold8a86fa52013-01-15 12:35:05 -08001224 // Advance the download progress to reflect what doesn't need to be
1225 // re-downloaded.
1226 total_bytes_received_ += buffer_offset_;
1227
Darin Petkov61426142010-10-08 11:04:55 -07001228 // Speculatively count the resume as a failure.
1229 int64_t resumed_update_failures;
1230 if (prefs_->GetInt64(kPrefsResumedUpdateFailures, &resumed_update_failures)) {
1231 resumed_update_failures++;
1232 } else {
1233 resumed_update_failures = 1;
1234 }
1235 prefs_->SetInt64(kPrefsResumedUpdateFailures, resumed_update_failures);
Darin Petkov9b230572010-10-08 10:20:09 -07001236 return true;
1237}
1238
Jay Srinivasanedce2832012-10-24 18:57:47 -07001239void DeltaPerformer::SendUmaStat(ActionExitCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001240 utils::SendErrorCodeToUma(system_state_, code);
Jay Srinivasanf0572052012-10-23 18:12:56 -07001241}
1242
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001243} // namespace chromeos_update_engine