blob: ca694edf6dd4e81fc4adf60df57b1e7f9377ce6d [file] [log] [blame]
Andrew de los Reyes09e56d62010-04-23 13:45:53 -07001// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_DELTA_PERFORMER_H__
6#define CHROMEOS_PLATFORM_UPDATE_ENGINE_DELTA_PERFORMER_H__
7
8#include <inttypes.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -07009
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070010#include <vector>
Darin Petkovd7061ab2010-10-06 14:37:09 -070011
Gilad Arnold8a86fa52013-01-15 12:35:05 -080012#include <base/time.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070013#include <google/protobuf/repeated_field.h>
Andrew de los Reyes353777c2010-10-08 10:34:30 -070014#include <gtest/gtest_prod.h> // for FRIEND_TEST
Darin Petkovd7061ab2010-10-06 14:37:09 -070015
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070016#include "update_engine/file_writer.h"
Jay Srinivasan51dcf262012-09-13 17:24:32 -070017#include "update_engine/install_plan.h"
Darin Petkovd7061ab2010-10-06 14:37:09 -070018#include "update_engine/omaha_hash_calculator.h"
Jay Srinivasanf0572052012-10-23 18:12:56 -070019#include "update_engine/system_state.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070020#include "update_engine/update_metadata.pb.h"
21
22namespace chromeos_update_engine {
23
Darin Petkov73058b42010-10-06 16:32:19 -070024class PrefsInterface;
25
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026// This class performs the actions in a delta update synchronously. The delta
27// update itself should be passed in in chunks as it is received.
28
29class DeltaPerformer : public FileWriter {
30 public:
Darin Petkov9574f7e2011-01-13 10:48:12 -080031 enum MetadataParseResult {
32 kMetadataParseSuccess,
33 kMetadataParseError,
34 kMetadataParseInsufficientData,
35 };
36
Jay Srinivasanf4318702012-09-24 11:56:24 -070037 static const uint64_t kDeltaVersionSize;
38 static const uint64_t kDeltaManifestSizeSize;
Don Garrett4d039442013-10-28 18:40:06 -070039 static const uint64_t kSupportedMajorPayloadVersion;
Darin Petkovabc7bc02011-02-23 14:39:43 -080040 static const char kUpdatePayloadPublicKeyPath[];
41
Gilad Arnold8a86fa52013-01-15 12:35:05 -080042 // Defines the granularity of progress logging in terms of how many "completed
43 // chunks" we want to report at the most.
44 static const unsigned kProgressLogMaxChunks;
45 // Defines a timeout since the last progress was logged after which we want to
46 // force another log message (even if the current chunk was not completed).
47 static const unsigned kProgressLogTimeoutSeconds;
48 // These define the relative weights (0-100) we give to the different work
49 // components associated with an update when computing an overall progress.
50 // Currently they include the download progress and the number of completed
51 // operations. They must add up to one hundred (100).
52 static const unsigned kProgressDownloadWeight;
53 static const unsigned kProgressOperationsWeight;
54
Jay Srinivasanf0572052012-10-23 18:12:56 -070055 DeltaPerformer(PrefsInterface* prefs,
56 SystemState* system_state,
57 InstallPlan* install_plan)
Darin Petkov73058b42010-10-06 16:32:19 -070058 : prefs_(prefs),
Jay Srinivasanf0572052012-10-23 18:12:56 -070059 system_state_(system_state),
Jay Srinivasan51dcf262012-09-13 17:24:32 -070060 install_plan_(install_plan),
Darin Petkov73058b42010-10-06 16:32:19 -070061 fd_(-1),
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070062 kernel_fd_(-1),
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070063 manifest_valid_(false),
Darin Petkov437adc42010-10-07 13:12:24 -070064 manifest_metadata_size_(0),
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070065 next_operation_num_(0),
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070066 buffer_offset_(0),
Darin Petkov0406e402010-10-06 21:33:11 -070067 last_updated_buffer_offset_(kuint64max),
Jay Srinivasan51dcf262012-09-13 17:24:32 -070068 block_size_(0),
Gilad Arnold8a86fa52013-01-15 12:35:05 -080069 public_key_path_(kUpdatePayloadPublicKeyPath),
70 total_bytes_received_(0),
71 num_rootfs_operations_(0),
72 num_total_operations_(0),
73 overall_progress_(0),
74 last_progress_chunk_(0),
75 forced_progress_log_wait_(
76 base::TimeDelta::FromSeconds(kProgressLogTimeoutSeconds)) {}
Darin Petkovd7061ab2010-10-06 14:37:09 -070077
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070078 // Opens the kernel. Should be called before or after Open(), but before
79 // Write(). The kernel file will be close()d when Close() is called.
80 bool OpenKernel(const char* kernel_path);
81
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070082 // flags and mode ignored. Once Close()d, a DeltaPerformer can't be
83 // Open()ed again.
84 int Open(const char* path, int flags, mode_t mode);
85
Jay Srinivasan51dcf262012-09-13 17:24:32 -070086 // FileWriter's Write implementation where caller doesn't care about
87 // error codes.
88 bool Write(const void* bytes, size_t count) {
David Zeuthena99981f2013-04-29 13:42:47 -070089 ErrorCode error;
Jay Srinivasan51dcf262012-09-13 17:24:32 -070090 return Write(bytes, count, &error);
91 }
92
93 // FileWriter's Write implementation that returns a more specific |error| code
94 // in case of failures in Write operation.
David Zeuthena99981f2013-04-29 13:42:47 -070095 bool Write(const void* bytes, size_t count, ErrorCode *error);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070096
97 // Wrapper around close. Returns 0 on success or -errno on error.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070098 // Closes both 'path' given to Open() and the kernel path.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070099 int Close();
Darin Petkovd7061ab2010-10-06 14:37:09 -0700100
David Zeuthen8f191b22013-08-06 12:27:50 -0700101 // Returns |true| only if the manifest has been processed and it's valid.
102 bool IsManifestValid();
103
Darin Petkovd7061ab2010-10-06 14:37:09 -0700104 // Verifies the downloaded payload against the signed hash included in the
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700105 // payload, against the update check hash (which is in base64 format) and
David Zeuthena99981f2013-04-29 13:42:47 -0700106 // size using the public key and returns kErrorCodeSuccess on success, an
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700107 // error code on failure. This method should be called after closing the
108 // stream. Note this method skips the signed hash check if the public key is
David Zeuthena99981f2013-04-29 13:42:47 -0700109 // unavailable; it returns kErrorCodeSignedDeltaPayloadExpectedError if the
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700110 // public key is available but the delta payload doesn't include a signature.
David Zeuthena99981f2013-04-29 13:42:47 -0700111 ErrorCode VerifyPayload(const std::string& update_check_response_hash,
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700112 const uint64_t update_check_response_size);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700113
Darin Petkov3aefa862010-12-07 14:45:00 -0800114 // Reads from the update manifest the expected sizes and hashes of the target
115 // kernel and rootfs partitions. These values can be used for applied update
116 // hash verification. This method must be called after the update manifest has
117 // been parsed (e.g., after closing the stream). Returns true on success, and
118 // false on failure (e.g., when the values are not present in the update
119 // manifest).
120 bool GetNewPartitionInfo(uint64_t* kernel_size,
121 std::vector<char>* kernel_hash,
122 uint64_t* rootfs_size,
123 std::vector<char>* rootfs_hash);
Darin Petkov2dd01092010-10-08 15:43:05 -0700124
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700125 // Converts an ordered collection of Extent objects which contain data of
126 // length full_length to a comma-separated string. For each Extent, the
127 // string will have the start offset and then the length in bytes.
128 // The length value of the last extent in the string may be short, since
129 // the full length of all extents in the string is capped to full_length.
130 // Also, an extent starting at kSparseHole, appears as -1 in the string.
131 // For example, if the Extents are {1, 1}, {4, 2}, {kSparseHole, 1},
132 // {0, 1}, block_size is 4096, and full_length is 5 * block_size - 13,
133 // the resulting string will be: "4096:4096,16384:8192,-1:4096,0:4083"
134 static bool ExtentsToBsdiffPositionsString(
135 const google::protobuf::RepeatedPtrField<Extent>& extents,
136 uint64_t block_size,
137 uint64_t full_length,
138 std::string* positions_string);
139
Darin Petkov0406e402010-10-06 21:33:11 -0700140 // Returns true if a previous update attempt can be continued based on the
141 // persistent preferences and the new update check response hash.
142 static bool CanResumeUpdate(PrefsInterface* prefs,
143 std::string update_check_response_hash);
144
145 // Resets the persistent update progress state to indicate that an update
Darin Petkov9b230572010-10-08 10:20:09 -0700146 // can't be resumed. Performs a quick update-in-progress reset if |quick| is
147 // true, otherwise resets all progress-related update state. Returns true on
148 // success, false otherwise.
149 static bool ResetUpdateProgress(PrefsInterface* prefs, bool quick);
Darin Petkov0406e402010-10-06 21:33:11 -0700150
Darin Petkov9574f7e2011-01-13 10:48:12 -0800151 // Attempts to parse the update metadata starting from the beginning of
152 // |payload| into |manifest|. On success, sets |metadata_size| to the total
153 // metadata bytes (including the delta magic and metadata size fields), and
154 // returns kMetadataParseSuccess. Returns kMetadataParseInsufficientData if
155 // more data is needed to parse the complete metadata. Returns
156 // kMetadataParseError if the metadata can't be parsed given the payload.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700157 MetadataParseResult ParsePayloadMetadata(
Darin Petkov9574f7e2011-01-13 10:48:12 -0800158 const std::vector<char>& payload,
159 DeltaArchiveManifest* manifest,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700160 uint64_t* metadata_size,
David Zeuthena99981f2013-04-29 13:42:47 -0700161 ErrorCode* error);
Darin Petkov9574f7e2011-01-13 10:48:12 -0800162
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700163 void set_public_key_path(const std::string& public_key_path) {
164 public_key_path_ = public_key_path;
Darin Petkov698d0412010-10-13 10:59:44 -0700165 }
166
Don Garrett4d039442013-10-28 18:40:06 -0700167 // Returns the byte offset at which the payload version can be found.
168 static uint64_t GetVersionOffset();
Jay Srinivasanf4318702012-09-24 11:56:24 -0700169
170 // Returns the byte offset where the size of the manifest is stored in
171 // a payload. This offset precedes the actual start of the manifest
172 // that's returned by the GetManifestOffset method.
173 static uint64_t GetManifestSizeOffset();
174
Don Garrett4d039442013-10-28 18:40:06 -0700175 // Returns the byte offset at which the manifest protobuf begins in a
176 // payload.
177 static uint64_t GetManifestOffset();
178
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700179 private:
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700180 friend class DeltaPerformerTest;
181 FRIEND_TEST(DeltaPerformerTest, IsIdempotentOperationTest);
David Zeuthene7f89172013-10-31 10:21:04 -0700182 FRIEND_TEST(DeltaPerformerTest, UsePublicKeyFromResponse);
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700183
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800184 // Logs the progress of downloading/applying an update.
185 void LogProgress(const char* message_prefix);
186
187 // Update overall progress metrics, log as necessary.
188 void UpdateOverallProgress(bool force_log, const char* message_prefix);
189
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700190 static bool IsIdempotentOperation(
191 const DeltaArchiveManifest_InstallOperation& op);
192
Darin Petkov698d0412010-10-13 10:59:44 -0700193 // Verifies that the expected source partition hashes (if present) match the
194 // hashes for the current partitions. Returns true if there're no expected
195 // hashes in the payload (e.g., if it's a new-style full update) or if the
196 // hashes match; returns false otherwise.
197 bool VerifySourcePartitions();
198
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700199 // Returns true if enough of the delta file has been passed via Write()
200 // to be able to perform a given install operation.
201 bool CanPerformInstallOperation(
202 const DeltaArchiveManifest_InstallOperation& operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700203
Gilad Arnold21504f02013-05-24 08:51:22 -0700204 // Checks the integrity of the payload manifest. Returns true upon success,
205 // false otherwise.
206 ErrorCode ValidateManifest();
207
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700208 // Validates that the hash of the blobs corresponding to the given |operation|
209 // matches what's specified in the manifest in the payload.
David Zeuthena99981f2013-04-29 13:42:47 -0700210 // Returns kErrorCodeSuccess on match or a suitable error code otherwise.
211 ErrorCode ValidateOperationHash(
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800212 const DeltaArchiveManifest_InstallOperation& operation);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700213
214 // Interprets the given |protobuf| as a DeltaArchiveManifest protocol buffer
215 // of the given protobuf_length and verifies that the signed hash of the
Jay Srinivasanf4318702012-09-24 11:56:24 -0700216 // metadata matches what's specified in the install plan from Omaha.
David Zeuthena99981f2013-04-29 13:42:47 -0700217 // Returns kErrorCodeSuccess on match or a suitable error code otherwise.
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700218 // This method must be called before any part of the |protobuf| is parsed
219 // so that a man-in-the-middle attack on the SSL connection to the payload
220 // server doesn't exploit any vulnerability in the code that parses the
221 // protocol buffer.
David Zeuthena99981f2013-04-29 13:42:47 -0700222 ErrorCode ValidateMetadataSignature(const char* protobuf,
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700223 uint64_t protobuf_length);
224
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700225 // Returns true on success.
226 bool PerformInstallOperation(
227 const DeltaArchiveManifest_InstallOperation& operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700228
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700229 // These perform a specific type of operation and return true on success.
230 bool PerformReplaceOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700231 const DeltaArchiveManifest_InstallOperation& operation,
232 bool is_kernel_partition);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700233 bool PerformMoveOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700234 const DeltaArchiveManifest_InstallOperation& operation,
235 bool is_kernel_partition);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700236 bool PerformBsdiffOperation(
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700237 const DeltaArchiveManifest_InstallOperation& operation,
238 bool is_kernel_partition);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700239
Darin Petkovd7061ab2010-10-06 14:37:09 -0700240 // Returns true if the payload signature message has been extracted from
241 // |operation|, false otherwise.
242 bool ExtractSignatureMessage(
243 const DeltaArchiveManifest_InstallOperation& operation);
244
Darin Petkov437adc42010-10-07 13:12:24 -0700245 // Updates the hash calculator with |count| bytes at the head of |buffer_| and
246 // then discards them.
247 void DiscardBufferHeadBytes(size_t count);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700248
Darin Petkov0406e402010-10-06 21:33:11 -0700249 // Checkpoints the update progress into persistent storage to allow this
250 // update attempt to be resumed after reboot.
Darin Petkov73058b42010-10-06 16:32:19 -0700251 bool CheckpointUpdateProgress();
252
Darin Petkov9b230572010-10-08 10:20:09 -0700253 // Primes the required update state. Returns true if the update state was
254 // successfully initialized to a saved resume state or if the update is a new
255 // update. Returns false otherwise.
256 bool PrimeUpdateState();
257
Jay Srinivasanf0572052012-10-23 18:12:56 -0700258 // Sends UMA statistics for the given error code.
David Zeuthena99981f2013-04-29 13:42:47 -0700259 void SendUmaStat(ErrorCode code);
Jay Srinivasanf0572052012-10-23 18:12:56 -0700260
David Zeuthene7f89172013-10-31 10:21:04 -0700261 // If the Omaha response contains a public RSA key and we're allowed
262 // to use it (e.g. if we're in developer mode), extract the key from
263 // the response and store it in a temporary file and return true. In
264 // the affirmative the path to the temporary file is stored in
265 // |out_tmp_key| and it is the responsibility of the caller to clean
266 // it up.
267 bool GetPublicKeyFromResponse(base::FilePath *out_tmp_key);
268
Darin Petkov73058b42010-10-06 16:32:19 -0700269 // Update Engine preference store.
270 PrefsInterface* prefs_;
271
Jay Srinivasanf0572052012-10-23 18:12:56 -0700272 // Global context of the system.
273 SystemState* system_state_;
274
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700275 // Install Plan based on Omaha Response.
276 InstallPlan* install_plan_;
277
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700278 // File descriptor of open device.
279 int fd_;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700280
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700281 // File descriptor of the kernel device
282 int kernel_fd_;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700283
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700284 std::string path_; // Path that fd_ refers to.
285 std::string kernel_path_; // Path that kernel_fd_ refers to.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700286
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700287 DeltaArchiveManifest manifest_;
288 bool manifest_valid_;
Darin Petkov437adc42010-10-07 13:12:24 -0700289 uint64_t manifest_metadata_size_;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700290
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700291 // Index of the next operation to perform in the manifest.
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800292 size_t next_operation_num_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700293
294 // buffer_ is a window of the data that's been downloaded. At first,
295 // it contains the beginning of the download, but after the protobuf
296 // has been downloaded and parsed, it contains a sliding window of
297 // data blobs.
298 std::vector<char> buffer_;
299 // Offset of buffer_ in the binary blobs section of the update.
300 uint64_t buffer_offset_;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700301
Darin Petkov0406e402010-10-06 21:33:11 -0700302 // Last |buffer_offset_| value updated as part of the progress update.
303 uint64_t last_updated_buffer_offset_;
304
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700305 // The block size (parsed from the manifest).
306 uint32_t block_size_;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700307
Darin Petkov437adc42010-10-07 13:12:24 -0700308 // Calculates the payload hash.
Darin Petkovd7061ab2010-10-06 14:37:09 -0700309 OmahaHashCalculator hash_calculator_;
310
Darin Petkov437adc42010-10-07 13:12:24 -0700311 // Saves the signed hash context.
312 std::string signed_hash_context_;
313
Darin Petkovd7061ab2010-10-06 14:37:09 -0700314 // Signatures message blob extracted directly from the payload.
315 std::vector<char> signatures_message_data_;
316
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700317 // The public key to be used. Provided as a member so that tests can
318 // override with test keys.
319 std::string public_key_path_;
Darin Petkov698d0412010-10-13 10:59:44 -0700320
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800321 // The number of bytes received so far, used for progress tracking.
322 size_t total_bytes_received_;
323
324 // The number rootfs and total operations in a payload, once we know them.
325 size_t num_rootfs_operations_;
326 size_t num_total_operations_;
327
328 // An overall progress counter, which should reflect both download progress
329 // and the ratio of applied operations. Range is 0-100.
330 unsigned overall_progress_;
331
332 // The last progress chunk recorded.
333 unsigned last_progress_chunk_;
334
335 // The timeout after which we should force emitting a progress log (constant),
336 // and the actual point in time for the next forced log to be emitted.
337 const base::TimeDelta forced_progress_log_wait_;
338 base::Time forced_progress_log_time_;
339
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700340 DISALLOW_COPY_AND_ASSIGN(DeltaPerformer);
341};
342
343} // namespace chromeos_update_engine
344
345#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_DELTA_PERFORMER_H__