blob: bee7fdea9c76a6361bfedd8d0e40c0edd2e4d68e [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2010 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#ifndef UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_
18#define UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070019
20#include <inttypes.h>
Darin Petkovd7061ab2010-10-06 14:37:09 -070021
Amin Hassanidb56be92017-09-06 12:41:23 -070022#include <limits>
Tianjie Xu7a78d632019-10-08 16:32:39 -070023#include <memory>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070024#include <string>
Tianjie Xu7a78d632019-10-08 16:32:39 -070025#include <utility>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070026#include <vector>
Darin Petkovd7061ab2010-10-06 14:37:09 -070027
Alex Vakulenko75039d72014-03-25 12:36:28 -070028#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070029#include <brillo/secure_blob.h>
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070030#include <google/protobuf/repeated_field.h>
Andrew de los Reyes353777c2010-10-08 10:34:30 -070031#include <gtest/gtest_prod.h> // for FRIEND_TEST
Darin Petkovd7061ab2010-10-06 14:37:09 -070032
Alex Deymo39910dc2015-11-09 17:04:30 -080033#include "update_engine/common/hash_calculator.h"
34#include "update_engine/common/platform_constants.h"
35#include "update_engine/payload_consumer/file_descriptor.h"
36#include "update_engine/payload_consumer/file_writer.h"
37#include "update_engine/payload_consumer/install_plan.h"
Sen Jiangb5f601d2018-02-02 13:51:21 -080038#include "update_engine/payload_consumer/payload_metadata.h"
Tianjie Xu7a78d632019-10-08 16:32:39 -070039#include "update_engine/payload_consumer/payload_verifier.h"
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070040#include "update_engine/update_metadata.pb.h"
41
42namespace chromeos_update_engine {
43
Alex Deymo542c19b2015-12-03 07:43:31 -030044class DownloadActionDelegate;
45class BootControlInterface;
46class HardwareInterface;
Darin Petkov73058b42010-10-06 16:32:19 -070047class PrefsInterface;
48
Kelvin Zhang9bd519d2020-09-23 12:55:19 -040049// At the bottom of this file.
50class PartitionWriter;
51
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070052// This class performs the actions in a delta update synchronously. The delta
53// update itself should be passed in in chunks as it is received.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070054class DeltaPerformer : public FileWriter {
55 public:
Gilad Arnold8a86fa52013-01-15 12:35:05 -080056 // Defines the granularity of progress logging in terms of how many "completed
57 // chunks" we want to report at the most.
58 static const unsigned kProgressLogMaxChunks;
59 // Defines a timeout since the last progress was logged after which we want to
60 // force another log message (even if the current chunk was not completed).
61 static const unsigned kProgressLogTimeoutSeconds;
62 // These define the relative weights (0-100) we give to the different work
63 // components associated with an update when computing an overall progress.
64 // Currently they include the download progress and the number of completed
65 // operations. They must add up to one hundred (100).
66 static const unsigned kProgressDownloadWeight;
67 static const unsigned kProgressOperationsWeight;
Colin Howes0e452c92018-11-02 13:18:44 -070068 static const uint64_t kCheckpointFrequencySeconds;
Gilad Arnold8a86fa52013-01-15 12:35:05 -080069
Jay Srinivasanf0572052012-10-23 18:12:56 -070070 DeltaPerformer(PrefsInterface* prefs,
Alex Deymo542c19b2015-12-03 07:43:31 -030071 BootControlInterface* boot_control,
72 HardwareInterface* hardware,
73 DownloadActionDelegate* download_delegate,
Sen Jiang0affc2c2017-02-10 15:55:05 -080074 InstallPlan* install_plan,
Sen Jiang18414082018-01-11 14:50:36 -080075 InstallPlan::Payload* payload,
Amin Hassanied37d682018-04-06 13:22:00 -070076 bool interactive)
Darin Petkov73058b42010-10-06 16:32:19 -070077 : prefs_(prefs),
Alex Deymo542c19b2015-12-03 07:43:31 -030078 boot_control_(boot_control),
79 hardware_(hardware),
80 download_delegate_(download_delegate),
Sen Jiang0affc2c2017-02-10 15:55:05 -080081 install_plan_(install_plan),
Sen Jiang18414082018-01-11 14:50:36 -080082 payload_(payload),
Kelvin Zhangcc011d32020-07-10 18:20:08 -040083 interactive_(interactive) {
84 CHECK(install_plan_);
85 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070086
Jay Srinivasan51dcf262012-09-13 17:24:32 -070087 // FileWriter's Write implementation where caller doesn't care about
88 // error codes.
Alex Deymo610277e2014-11-11 21:18:11 -080089 bool Write(const void* bytes, size_t count) override {
David Zeuthena99981f2013-04-29 13:42:47 -070090 ErrorCode error;
Jay Srinivasan51dcf262012-09-13 17:24:32 -070091 return Write(bytes, count, &error);
92 }
93
94 // FileWriter's Write implementation that returns a more specific |error| code
95 // in case of failures in Write operation.
Amin Hassani008c4582019-01-13 16:22:47 -080096 bool Write(const void* bytes, size_t count, ErrorCode* error) override;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070097
98 // Wrapper around close. Returns 0 on success or -errno on error.
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -070099 // Closes both 'path' given to Open() and the kernel path.
Alex Deymo610277e2014-11-11 21:18:11 -0800100 int Close() override;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700101
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700102 // Open the target and source (if delta payload) file descriptors for the
103 // |current_partition_|. The manifest needs to be already parsed for this to
104 // work. Returns whether the required file descriptors were successfully open.
105 bool OpenCurrentPartition();
106
107 // Closes the current partition file descriptors if open. Returns 0 on success
108 // or -errno on error.
109 int CloseCurrentPartition();
110
David Zeuthen8f191b22013-08-06 12:27:50 -0700111 // Returns |true| only if the manifest has been processed and it's valid.
112 bool IsManifestValid();
113
Darin Petkovd7061ab2010-10-06 14:37:09 -0700114 // Verifies the downloaded payload against the signed hash included in the
Sen Jiang2703ef42017-03-16 13:36:21 -0700115 // payload, against the update check hash and size using the public key and
116 // returns ErrorCode::kSuccess on success, an error code on failure.
117 // This method should be called after closing the stream. Note this method
118 // skips the signed hash check if the public key is unavailable; it returns
119 // ErrorCode::kSignedDeltaPayloadExpectedError if the public key is available
120 // but the delta payload doesn't include a signature.
121 ErrorCode VerifyPayload(const brillo::Blob& update_check_response_hash,
Allie Wood9f6f0a52015-03-30 11:25:47 -0700122 const uint64_t update_check_response_size);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700123
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700124 // Converts an ordered collection of Extent objects which contain data of
125 // length full_length to a comma-separated string. For each Extent, the
126 // string will have the start offset and then the length in bytes.
127 // The length value of the last extent in the string may be short, since
128 // the full length of all extents in the string is capped to full_length.
129 // Also, an extent starting at kSparseHole, appears as -1 in the string.
130 // For example, if the Extents are {1, 1}, {4, 2}, {kSparseHole, 1},
131 // {0, 1}, block_size is 4096, and full_length is 5 * block_size - 13,
132 // the resulting string will be: "4096:4096,16384:8192,-1:4096,0:4083"
133 static bool ExtentsToBsdiffPositionsString(
134 const google::protobuf::RepeatedPtrField<Extent>& extents,
135 uint64_t block_size,
136 uint64_t full_length,
137 std::string* positions_string);
138
Darin Petkov0406e402010-10-06 21:33:11 -0700139 // Returns true if a previous update attempt can be continued based on the
140 // persistent preferences and the new update check response hash.
141 static bool CanResumeUpdate(PrefsInterface* prefs,
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700142 const std::string& update_check_response_hash);
Darin Petkov0406e402010-10-06 21:33:11 -0700143
144 // Resets the persistent update progress state to indicate that an update
Darin Petkov9b230572010-10-08 10:20:09 -0700145 // can't be resumed. Performs a quick update-in-progress reset if |quick| is
Yifan Hong55c2bfe2020-01-13 17:01:19 -0800146 // true, otherwise resets all progress-related update state.
147 // If |skip_dynamic_partititon_metadata_updated| is true, do not reset
148 // dynamic-partition-metadata-updated.
149 // Returns true on success, false otherwise.
150 static bool ResetUpdateProgress(
151 PrefsInterface* prefs,
152 bool quick,
153 bool skip_dynamic_partititon_metadata_updated = false);
Darin Petkov0406e402010-10-06 21:33:11 -0700154
Darin Petkov9574f7e2011-01-13 10:48:12 -0800155 // Attempts to parse the update metadata starting from the beginning of
Gilad Arnolddaa27402014-01-23 11:56:17 -0800156 // |payload|. On success, returns kMetadataParseSuccess. Returns
Gilad Arnoldfe133932014-01-14 12:25:50 -0800157 // kMetadataParseInsufficientData if more data is needed to parse the complete
158 // metadata. Returns kMetadataParseError if the metadata can't be parsed given
159 // the payload.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700160 MetadataParseResult ParsePayloadMetadata(const brillo::Blob& payload,
Gilad Arnolddaa27402014-01-23 11:56:17 -0800161 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
Tianjie Xu7a78d632019-10-08 16:32:39 -0700167 void set_update_certificates_path(
168 const std::string& update_certificates_path) {
169 update_certificates_path_ = update_certificates_path;
170 }
171
Sen Jiangb8060e42015-09-24 17:30:50 -0700172 // Return true if header parsing is finished and no errors occurred.
173 bool IsHeaderParsed() const;
174
Allie Woodfdf00512015-03-02 13:34:55 -0800175 // Returns the delta minor version. If this value is defined in the manifest,
176 // it returns that value, otherwise it returns the default value.
177 uint32_t GetMinorVersion() const;
178
Yifan Hongb9d63572020-01-09 17:50:46 -0800179 // Initialize partitions and allocate required space for an update with the
180 // given |manifest|. |update_check_response_hash| is used to check if the
181 // previous call to this function corresponds to the same payload.
182 // - Same payload: not make any persistent modifications (not write to disk)
183 // - Different payload: make persistent modifications (write to disk)
184 // In both cases, in-memory flags are updated. This function must be called
185 // on the payload at least once (to update in-memory flags) before writing
186 // (applying) the payload.
187 // If error due to insufficient space, |required_size| is set to the required
188 // size on the device to apply the payload.
189 static bool PreparePartitionsForUpdate(
190 PrefsInterface* prefs,
191 BootControlInterface* boot_control,
192 BootControlInterface::Slot target_slot,
193 const DeltaArchiveManifest& manifest,
194 const std::string& update_check_response_hash,
195 uint64_t* required_size);
196
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700197 private:
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700198 friend class DeltaPerformerTest;
Sen Jianga4365d62015-09-25 10:52:25 -0700199 friend class DeltaPerformerIntegrationTest;
Sen Jiang76bfa742015-10-12 17:13:26 -0700200 FRIEND_TEST(DeltaPerformerTest, BrilloMetadataSignatureSizeTest);
Sen Jiangb5f601d2018-02-02 13:51:21 -0800201 FRIEND_TEST(DeltaPerformerTest, BrilloParsePayloadMetadataTest);
David Zeuthene7f89172013-10-31 10:21:04 -0700202 FRIEND_TEST(DeltaPerformerTest, UsePublicKeyFromResponse);
Andrew de los Reyes353777c2010-10-08 10:34:30 -0700203
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700204 // Parse and move the update instructions of all partitions into our local
205 // |partitions_| variable based on the version of the payload. Requires the
206 // manifest to be parsed and valid.
207 bool ParseManifestPartitions(ErrorCode* error);
208
Gilad Arnoldfe133932014-01-14 12:25:50 -0800209 // Appends up to |*count_p| bytes from |*bytes_p| to |buffer_|, but only to
210 // the extent that the size of |buffer_| does not exceed |max|. Advances
211 // |*cbytes_p| and decreases |*count_p| by the actual number of bytes copied,
212 // and returns this number.
213 size_t CopyDataToBuffer(const char** bytes_p, size_t* count_p, size_t max);
214
215 // If |op_result| is false, emits an error message using |op_type_name| and
216 // sets |*error| accordingly. Otherwise does nothing. Returns |op_result|.
Amin Hassani008c4582019-01-13 16:22:47 -0800217 bool HandleOpResult(bool op_result,
218 const char* op_type_name,
Gilad Arnoldfe133932014-01-14 12:25:50 -0800219 ErrorCode* error);
220
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800221 // Logs the progress of downloading/applying an update.
222 void LogProgress(const char* message_prefix);
223
224 // Update overall progress metrics, log as necessary.
225 void UpdateOverallProgress(bool force_log, const char* message_prefix);
226
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700227 // Returns true if enough of the delta file has been passed via Write()
228 // to be able to perform a given install operation.
Alex Deymoa12ee112015-08-12 22:19:32 -0700229 bool CanPerformInstallOperation(const InstallOperation& operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700230
Gilad Arnold21504f02013-05-24 08:51:22 -0700231 // Checks the integrity of the payload manifest. Returns true upon success,
232 // false otherwise.
233 ErrorCode ValidateManifest();
234
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700235 // Validates that the hash of the blobs corresponding to the given |operation|
236 // matches what's specified in the manifest in the payload.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700237 // Returns ErrorCode::kSuccess on match or a suitable error code otherwise.
Alex Deymoa12ee112015-08-12 22:19:32 -0700238 ErrorCode ValidateOperationHash(const InstallOperation& operation);
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700239
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700240 // Returns true on success.
Alex Deymoa12ee112015-08-12 22:19:32 -0700241 bool PerformInstallOperation(const InstallOperation& operation);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700242
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700243 // These perform a specific type of operation and return true on success.
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700244 // |error| will be set if source hash mismatch, otherwise |error| might not be
245 // set even if it fails.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700246 bool PerformReplaceOperation(const InstallOperation& operation);
247 bool PerformZeroOrDiscardOperation(const InstallOperation& operation);
Sen Jiangbe2c47b2016-06-15 14:09:27 -0700248 bool PerformSourceCopyOperation(const InstallOperation& operation,
249 ErrorCode* error);
250 bool PerformSourceBsdiffOperation(const InstallOperation& operation,
251 ErrorCode* error);
Amin Hassani02855c22017-09-06 22:34:50 -0700252 bool PerformPuffDiffOperation(const InstallOperation& operation,
253 ErrorCode* error);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700254
Sen Jiangf6813802015-11-03 21:27:29 -0800255 // Extracts the payload signature message from the current |buffer_| if the
256 // offset matches the one specified by the manifest. Returns whether the
257 // signature was extracted.
258 bool ExtractSignatureMessage();
259
260 // Updates the payload hash calculator with the bytes in |buffer_|, also
261 // updates the signed hash calculator with the first |signed_hash_buffer_size|
262 // bytes in |buffer_|. Then discard the content, ensuring that memory is being
263 // deallocated. If |do_advance_offset|, advances the internal offset counter
264 // accordingly.
265 void DiscardBuffer(bool do_advance_offset, size_t signed_hash_buffer_size);
Darin Petkovd7061ab2010-10-06 14:37:09 -0700266
Darin Petkov0406e402010-10-06 21:33:11 -0700267 // Checkpoints the update progress into persistent storage to allow this
268 // update attempt to be resumed after reboot.
Sen Jiang3a25dc22019-01-10 14:14:41 -0800269 // If |force| is false, checkpoint may be throttled.
270 bool CheckpointUpdateProgress(bool force);
Darin Petkov73058b42010-10-06 16:32:19 -0700271
Darin Petkov9b230572010-10-08 10:20:09 -0700272 // Primes the required update state. Returns true if the update state was
273 // successfully initialized to a saved resume state or if the update is a new
274 // update. Returns false otherwise.
275 bool PrimeUpdateState();
276
Sen Jiang08c6da12019-01-07 18:28:56 -0800277 // Get the public key to be used to verify metadata signature or payload
278 // signature. Always use |public_key_path_| if exists, otherwise if the Omaha
279 // response contains a public RSA key and we're allowed to use it (e.g. if
280 // we're in developer mode), decode the key from the response and store it in
281 // |out_public_key|. Returns false on failures.
282 bool GetPublicKey(std::string* out_public_key);
David Zeuthene7f89172013-10-31 10:21:04 -0700283
Tianjie Xu7a78d632019-10-08 16:32:39 -0700284 // Creates a PayloadVerifier from the zip file containing certificates. If the
285 // path to the zip file doesn't exist, falls back to use the public key.
286 // Returns a tuple with the created PayloadVerifier and if we should perform
287 // the verification.
288 std::pair<std::unique_ptr<PayloadVerifier>, bool> CreatePayloadVerifier();
289
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700290 // After install_plan_ is filled with partition names and sizes, initialize
291 // metadata of partitions and map necessary devices before opening devices.
Yifan Hongb9d63572020-01-09 17:50:46 -0800292 // Also see comment for the static PreparePartitionsForUpdate().
293 bool PreparePartitionsForUpdate(uint64_t* required_size);
Yifan Hong9acd9cb2018-10-19 14:52:45 -0700294
Yifan Hong87029332020-09-01 17:20:08 -0700295 // Check if current manifest contains timestamp errors.
296 // Return:
297 // - kSuccess if update is valid.
298 // - kPayloadTimestampError if downgrade is detected
299 // - kDownloadManifestParseError if |new_version| has an incorrect format
300 // - Other error values if the source of error is known, or kError for
301 // a generic error on the device.
302 ErrorCode CheckTimestampError() const;
Kelvin Zhangd7191032020-08-11 10:48:16 -0400303
Darin Petkov73058b42010-10-06 16:32:19 -0700304 // Update Engine preference store.
305 PrefsInterface* prefs_;
306
Alex Deymo542c19b2015-12-03 07:43:31 -0300307 // BootControl and Hardware interface references.
308 BootControlInterface* boot_control_;
309 HardwareInterface* hardware_;
310
311 // The DownloadActionDelegate instance monitoring the DownloadAction, or a
312 // nullptr if not used.
313 DownloadActionDelegate* download_delegate_;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700314
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700315 // Install Plan based on Omaha Response.
316 InstallPlan* install_plan_;
317
Sen Jiang0affc2c2017-02-10 15:55:05 -0800318 // Pointer to the current payload in install_plan_.payloads.
319 InstallPlan::Payload* payload_{nullptr};
320
Sen Jiangb5f601d2018-02-02 13:51:21 -0800321 PayloadMetadata payload_metadata_;
322
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700323 // Parsed manifest. Set after enough bytes to parse the manifest were
324 // downloaded.
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700325 DeltaArchiveManifest manifest_;
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700326 bool manifest_parsed_{false};
327 bool manifest_valid_{false};
328 uint64_t metadata_size_{0};
Sen Jiang76bfa742015-10-12 17:13:26 -0700329 uint32_t metadata_signature_size_{0};
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700330 uint64_t major_payload_version_{0};
Darin Petkovd7061ab2010-10-06 14:37:09 -0700331
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700332 // Accumulated number of operations per partition. The i-th element is the
333 // sum of the number of operations for all the partitions from 0 to i
334 // inclusive. Valid when |manifest_valid_| is true.
335 std::vector<size_t> acc_num_operations_;
336
337 // The total operations in a payload. Valid when |manifest_valid_| is true,
338 // otherwise 0.
339 size_t num_total_operations_{0};
340
341 // The list of partitions to update as found in the manifest major version 2.
342 // When parsing an older manifest format, the information is converted over to
343 // this format instead.
344 std::vector<PartitionUpdate> partitions_;
345
346 // Index in the list of partitions (|partitions_| member) of the current
347 // partition being processed.
348 size_t current_partition_{0};
349
350 // Index of the next operation to perform in the manifest. The index is linear
351 // on the total number of operation on the manifest.
352 size_t next_operation_num_{0};
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700353
Gilad Arnoldfe133932014-01-14 12:25:50 -0800354 // A buffer used for accumulating downloaded data. Initially, it stores the
355 // payload metadata; once that's downloaded and parsed, it stores data for the
356 // next update operation.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700357 brillo::Blob buffer_;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700358 // Offset of buffer_ in the binary blobs section of the update.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700359 uint64_t buffer_offset_{0};
Darin Petkovd7061ab2010-10-06 14:37:09 -0700360
Darin Petkov0406e402010-10-06 21:33:11 -0700361 // Last |buffer_offset_| value updated as part of the progress update.
Alex Vakulenko0103c362016-01-20 07:56:15 -0800362 uint64_t last_updated_buffer_offset_{std::numeric_limits<uint64_t>::max()};
Darin Petkov0406e402010-10-06 21:33:11 -0700363
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700364 // The block size (parsed from the manifest).
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700365 uint32_t block_size_{0};
Darin Petkovd7061ab2010-10-06 14:37:09 -0700366
Sen Jiangf6813802015-11-03 21:27:29 -0800367 // Calculates the whole payload file hash, including headers and signatures.
Alex Deymo39910dc2015-11-09 17:04:30 -0800368 HashCalculator payload_hash_calculator_;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700369
Sen Jiangf6813802015-11-03 21:27:29 -0800370 // Calculates the hash of the portion of the payload signed by the payload
371 // signature. This hash skips the metadata signature portion, located after
372 // the metadata and doesn't include the payload signature itself.
Alex Deymo39910dc2015-11-09 17:04:30 -0800373 HashCalculator signed_hash_calculator_;
Darin Petkov437adc42010-10-07 13:12:24 -0700374
Darin Petkovd7061ab2010-10-06 14:37:09 -0700375 // Signatures message blob extracted directly from the payload.
Sen Jiang9b2f1782019-01-24 14:27:50 -0800376 std::string signatures_message_data_;
Darin Petkovd7061ab2010-10-06 14:37:09 -0700377
Jay Srinivasan51dcf262012-09-13 17:24:32 -0700378 // The public key to be used. Provided as a member so that tests can
379 // override with test keys.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700380 std::string public_key_path_{constants::kUpdatePayloadPublicKeyPath};
Darin Petkov698d0412010-10-13 10:59:44 -0700381
Tianjie Xu7a78d632019-10-08 16:32:39 -0700382 // The path to the zip file with X509 certificates.
383 std::string update_certificates_path_{constants::kUpdateCertificatesPath};
384
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800385 // The number of bytes received so far, used for progress tracking.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700386 size_t total_bytes_received_{0};
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800387
388 // An overall progress counter, which should reflect both download progress
389 // and the ratio of applied operations. Range is 0-100.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700390 unsigned overall_progress_{0};
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800391
392 // The last progress chunk recorded.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700393 unsigned last_progress_chunk_{0};
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800394
Amin Hassani7ecda262017-07-11 17:10:50 -0700395 // If |true|, the update is user initiated (vs. periodic update checks).
Amin Hassanied37d682018-04-06 13:22:00 -0700396 bool interactive_{false};
Amin Hassani7ecda262017-07-11 17:10:50 -0700397
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800398 // The timeout after which we should force emitting a progress log (constant),
399 // and the actual point in time for the next forced log to be emitted.
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700400 const base::TimeDelta forced_progress_log_wait_{
401 base::TimeDelta::FromSeconds(kProgressLogTimeoutSeconds)};
Sen Jiang53c2ec52019-01-10 15:27:59 -0800402 base::TimeTicks forced_progress_log_time_;
Gilad Arnold8a86fa52013-01-15 12:35:05 -0800403
Colin Howes0e452c92018-11-02 13:18:44 -0700404 // The frequency that we should write an update checkpoint (constant), and
405 // the point in time at which the next checkpoint should be written.
406 const base::TimeDelta update_checkpoint_wait_{
407 base::TimeDelta::FromSeconds(kCheckpointFrequencySeconds)};
Sen Jiang53c2ec52019-01-10 15:27:59 -0800408 base::TimeTicks update_checkpoint_time_;
Colin Howes0e452c92018-11-02 13:18:44 -0700409
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400410 std::unique_ptr<PartitionWriter> partition_writer_;
411
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700412 DISALLOW_COPY_AND_ASSIGN(DeltaPerformer);
413};
414
Kelvin Zhang9bd519d2020-09-23 12:55:19 -0400415class PartitionWriter {
416 public:
417 PartitionWriter(const PartitionUpdate& partition_update,
418 const InstallPlan::Partition& install_part,
419 DynamicPartitionControlInterface* dynamic_control,
420 size_t block_size,
421 bool is_interactive);
422 ~PartitionWriter();
423 // Compare |calculated_hash| with source hash in |operation|, return false and
424 // dump hash and set |error| if don't match.
425 // |source_fd| is the file descriptor of the source partition.
426 static bool ValidateSourceHash(const brillo::Blob& calculated_hash,
427 const InstallOperation& operation,
428 const FileDescriptorPtr source_fd,
429 ErrorCode* error);
430
431 // Perform necessary initialization work before InstallOperation can be
432 // applied to this partition
433 [[nodiscard]] bool Init(const InstallPlan* install_plan,
434 bool source_may_exist);
435
436 int Close();
437
438 // These perform a specific type of operation and return true on success.
439 // |error| will be set if source hash mismatch, otherwise |error| might not be
440 // set even if it fails.
441 [[nodiscard]] bool PerformReplaceOperation(const InstallOperation& operation,
442 const void* data,
443 size_t count);
444 [[nodiscard]] bool PerformZeroOrDiscardOperation(
445 const InstallOperation& operation);
446
447 [[nodiscard]] bool PerformSourceCopyOperation(
448 const InstallOperation& operation, ErrorCode* error);
449 [[nodiscard]] bool PerformSourceBsdiffOperation(
450 const InstallOperation& operation,
451 ErrorCode* error,
452 const void* data,
453 size_t count);
454 [[nodiscard]] bool PerformPuffDiffOperation(const InstallOperation& operation,
455 ErrorCode* error,
456 const void* data,
457 size_t count);
458
459 private:
460 friend class PartitionWriterTest;
461 FRIEND_TEST(PartitionWriterTest, ChooseSourceFDTest);
462
463 bool OpenCurrentECCPartition();
464 // For a given operation, choose the source fd to be used (raw device or error
465 // correction device) based on the source operation hash.
466 // Returns nullptr if the source hash mismatch cannot be corrected, and set
467 // the |error| accordingly.
468 FileDescriptorPtr ChooseSourceFD(const InstallOperation& operation,
469 ErrorCode* error);
470
471 const PartitionUpdate& partition_update_;
472 const InstallPlan::Partition& install_part_;
473 DynamicPartitionControlInterface* dynamic_control_;
474 std::string source_path_;
475 std::string target_path_;
476 FileDescriptorPtr source_fd_;
477 FileDescriptorPtr target_fd_;
478 const bool interactive_;
479 const size_t block_size_;
480 // File descriptor of the error corrected source partition. Only set while
481 // updating partition using a delta payload for a partition where error
482 // correction is available. The size of the error corrected device is smaller
483 // than the underlying raw device, since it doesn't include the error
484 // correction blocks.
485 FileDescriptorPtr source_ecc_fd_{nullptr};
486
487 // The total number of operations that failed source hash verification but
488 // passed after falling back to the error-corrected |source_ecc_fd_| device.
489 uint64_t source_ecc_recovered_failures_{0};
490
491 // Whether opening the current partition as an error-corrected device failed.
492 // Used to avoid re-opening the same source partition if it is not actually
493 // error corrected.
494 bool source_ecc_open_failure_{false};
495};
496
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700497} // namespace chromeos_update_engine
498
Alex Deymo39910dc2015-11-09 17:04:30 -0800499#endif // UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_