1 // 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 // 16 17 #ifndef UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_ 18 #define UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_ 19 20 #include <inttypes.h> 21 22 #include <limits> 23 #include <memory> 24 #include <string> 25 #include <utility> 26 #include <vector> 27 28 #include <base/time/time.h> 29 #include <brillo/secure_blob.h> 30 #include <google/protobuf/repeated_field.h> 31 #include <gtest/gtest_prod.h> // for FRIEND_TEST 32 33 #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" 38 #include "update_engine/payload_consumer/partition_writer.h" 39 #include "update_engine/payload_consumer/payload_metadata.h" 40 #include "update_engine/payload_consumer/payload_verifier.h" 41 #include "update_engine/update_metadata.pb.h" 42 43 namespace chromeos_update_engine { 44 45 class DownloadActionDelegate; 46 class BootControlInterface; 47 class HardwareInterface; 48 class PrefsInterface; 49 50 // This class performs the actions in a delta update synchronously. The delta 51 // update itself should be passed in in chunks as it is received. 52 class DeltaPerformer : public FileWriter { 53 public: 54 // Defines the granularity of progress logging in terms of how many "completed 55 // chunks" we want to report at the most. 56 static const unsigned kProgressLogMaxChunks; 57 // Defines a timeout since the last progress was logged after which we want to 58 // force another log message (even if the current chunk was not completed). 59 static const unsigned kProgressLogTimeoutSeconds; 60 // These define the relative weights (0-100) we give to the different work 61 // components associated with an update when computing an overall progress. 62 // Currently they include the download progress and the number of completed 63 // operations. They must add up to one hundred (100). 64 static const unsigned kProgressDownloadWeight; 65 static const unsigned kProgressOperationsWeight; 66 static const uint64_t kCheckpointFrequencySeconds; 67 68 DeltaPerformer( 69 PrefsInterface* prefs, 70 BootControlInterface* boot_control, 71 HardwareInterface* hardware, 72 DownloadActionDelegate* download_delegate, 73 InstallPlan* install_plan, 74 InstallPlan::Payload* payload, 75 bool interactive, 76 std::string update_certificates_path = constants::kUpdateCertificatesPath) prefs_(prefs)77 : prefs_(prefs), 78 boot_control_(boot_control), 79 hardware_(hardware), 80 download_delegate_(download_delegate), 81 install_plan_(install_plan), 82 payload_(payload), 83 update_certificates_path_(std::move(update_certificates_path)), 84 interactive_(interactive) { 85 CHECK(install_plan_); 86 } 87 88 // FileWriter's Write implementation where caller doesn't care about 89 // error codes. Write(const void * bytes,size_t count)90 bool Write(const void* bytes, size_t count) override { 91 ErrorCode error; 92 return Write(bytes, count, &error); 93 } 94 95 // FileWriter's Write implementation that returns a more specific |error| code 96 // in case of failures in Write operation. 97 bool Write(const void* bytes, size_t count, ErrorCode* error) override; 98 99 // Wrapper around close. Returns 0 on success or -errno on error. 100 // Closes both 'path' given to Open() and the kernel path. 101 int Close() override; 102 103 // Open the target and source (if delta payload) file descriptors for the 104 // |current_partition_|. The manifest needs to be already parsed for this to 105 // work. Returns whether the required file descriptors were successfully open. 106 bool OpenCurrentPartition(); 107 108 // Closes the current partition file descriptors if open. Returns 0 on success 109 // or -errno on error. 110 int CloseCurrentPartition(); 111 112 // Returns |true| only if the manifest has been processed and it's valid. 113 bool IsManifestValid(); 114 115 // Verifies the downloaded payload against the signed hash included in the 116 // payload, against the update check hash and size using the public key and 117 // returns ErrorCode::kSuccess on success, an error code on failure. 118 // This method should be called after closing the stream. Note this method 119 // skips the signed hash check if the public key is unavailable; it returns 120 // ErrorCode::kSignedDeltaPayloadExpectedError if the public key is available 121 // but the delta payload doesn't include a signature. 122 ErrorCode VerifyPayload(const brillo::Blob& update_check_response_hash, 123 const uint64_t update_check_response_size); 124 125 // 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 140 // 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 const std::string& update_check_response_hash); 144 145 // Resets the persistent update progress state to indicate that an update 146 // can't be resumed. Performs a quick update-in-progress reset if |quick| is 147 // true, otherwise resets all progress-related update state. 148 // If |skip_dynamic_partititon_metadata_updated| is true, do not reset 149 // dynamic-partition-metadata-updated. 150 // Returns true on success, false otherwise. 151 static bool ResetUpdateProgress( 152 PrefsInterface* prefs, 153 bool quick, 154 bool skip_dynamic_partititon_metadata_updated = false); 155 156 // Attempts to parse the update metadata starting from the beginning of 157 // |payload|. On success, returns kMetadataParseSuccess. Returns 158 // kMetadataParseInsufficientData if more data is needed to parse the complete 159 // metadata. Returns kMetadataParseError if the metadata can't be parsed given 160 // the payload. 161 MetadataParseResult ParsePayloadMetadata(const brillo::Blob& payload, 162 ErrorCode* error); 163 set_public_key_path(const std::string & public_key_path)164 void set_public_key_path(const std::string& public_key_path) { 165 public_key_path_ = public_key_path; 166 } 167 168 // Return true if header parsing is finished and no errors occurred. 169 bool IsHeaderParsed() const; 170 171 // Checkpoints the update progress into persistent storage to allow this 172 // update attempt to be resumed after reboot. 173 // If |force| is false, checkpoint may be throttled. 174 // Exposed for testing purposes. 175 bool CheckpointUpdateProgress(bool force); 176 177 // Initialize partitions and allocate required space for an update with the 178 // given |manifest|. |update_check_response_hash| is used to check if the 179 // previous call to this function corresponds to the same payload. 180 // - Same payload: not make any persistent modifications (not write to disk) 181 // - Different payload: make persistent modifications (write to disk) 182 // In both cases, in-memory flags are updated. This function must be called 183 // on the payload at least once (to update in-memory flags) before writing 184 // (applying) the payload. 185 // If error due to insufficient space, |required_size| is set to the required 186 // size on the device to apply the payload. 187 static bool PreparePartitionsForUpdate( 188 PrefsInterface* prefs, 189 BootControlInterface* boot_control, 190 BootControlInterface::Slot target_slot, 191 const DeltaArchiveManifest& manifest, 192 const std::string& update_check_response_hash, 193 uint64_t* required_size); 194 195 protected: 196 // Exposed as virtual for testing purposes. 197 virtual std::unique_ptr<PartitionWriterInterface> CreatePartitionWriter( 198 const PartitionUpdate& partition_update, 199 const InstallPlan::Partition& install_part, 200 DynamicPartitionControlInterface* dynamic_control, 201 size_t block_size, 202 bool is_interactive, 203 bool is_dynamic_partition); 204 205 // return true if it has been long enough and a checkpoint should be saved. 206 // Exposed for unittest purposes. 207 virtual bool ShouldCheckpoint(); 208 209 private: 210 friend class DeltaPerformerTest; 211 friend class DeltaPerformerIntegrationTest; 212 FRIEND_TEST(DeltaPerformerTest, BrilloMetadataSignatureSizeTest); 213 FRIEND_TEST(DeltaPerformerTest, BrilloParsePayloadMetadataTest); 214 FRIEND_TEST(DeltaPerformerTest, UsePublicKeyFromResponse); 215 216 // Obtain the operation index for current partition. If all operations for 217 // current partition is are finished, return # of operations. This is mostly 218 // intended to be used by CheckpointUpdateProgress, where partition writer 219 // needs to know the current operation number to properly checkpoint update. 220 size_t GetPartitionOperationNum(); 221 222 // Parse and move the update instructions of all partitions into our local 223 // |partitions_| variable based on the version of the payload. Requires the 224 // manifest to be parsed and valid. 225 bool ParseManifestPartitions(ErrorCode* error); 226 227 // Appends up to |*count_p| bytes from |*bytes_p| to |buffer_|, but only to 228 // the extent that the size of |buffer_| does not exceed |max|. Advances 229 // |*cbytes_p| and decreases |*count_p| by the actual number of bytes copied, 230 // and returns this number. 231 size_t CopyDataToBuffer(const char** bytes_p, size_t* count_p, size_t max); 232 233 // If |op_result| is false, emits an error message using |op_type_name| and 234 // sets |*error| accordingly. Otherwise does nothing. Returns |op_result|. 235 bool HandleOpResult(bool op_result, 236 const char* op_type_name, 237 ErrorCode* error); 238 239 // Logs the progress of downloading/applying an update. 240 void LogProgress(const char* message_prefix); 241 242 // Update overall progress metrics, log as necessary. 243 void UpdateOverallProgress(bool force_log, const char* message_prefix); 244 245 // Returns true if enough of the delta file has been passed via Write() 246 // to be able to perform a given install operation. 247 bool CanPerformInstallOperation(const InstallOperation& operation); 248 249 // Checks the integrity of the payload manifest. Returns true upon success, 250 // false otherwise. 251 ErrorCode ValidateManifest(); 252 253 // Validates that the hash of the blobs corresponding to the given |operation| 254 // matches what's specified in the manifest in the payload. 255 // Returns ErrorCode::kSuccess on match or a suitable error code otherwise. 256 ErrorCode ValidateOperationHash(const InstallOperation& operation); 257 258 // Returns true on success. 259 bool PerformInstallOperation(const InstallOperation& operation); 260 261 // These perform a specific type of operation and return true on success. 262 // |error| will be set if source hash mismatch, otherwise |error| might not be 263 // set even if it fails. 264 bool PerformReplaceOperation(const InstallOperation& operation); 265 bool PerformZeroOrDiscardOperation(const InstallOperation& operation); 266 bool PerformSourceCopyOperation(const InstallOperation& operation, 267 ErrorCode* error); 268 bool PerformDiffOperation(const InstallOperation& operation, 269 ErrorCode* error); 270 271 // Extracts the payload signature message from the current |buffer_| if the 272 // offset matches the one specified by the manifest. Returns whether the 273 // signature was extracted. 274 bool ExtractSignatureMessage(); 275 276 // Updates the payload hash calculator with the bytes in |buffer_|, also 277 // updates the signed hash calculator with the first |signed_hash_buffer_size| 278 // bytes in |buffer_|. Then discard the content, ensuring that memory is being 279 // deallocated. If |do_advance_offset|, advances the internal offset counter 280 // accordingly. 281 void DiscardBuffer(bool do_advance_offset, size_t signed_hash_buffer_size); 282 283 // Primes the required update state. Returns true if the update state was 284 // successfully initialized to a saved resume state or if the update is a new 285 // update. Returns false otherwise. 286 bool PrimeUpdateState(); 287 288 // Get the public key to be used to verify metadata signature or payload 289 // signature. Always use |public_key_path_| if exists, otherwise if the Omaha 290 // response contains a public RSA key and we're allowed to use it (e.g. if 291 // we're in developer mode), decode the key from the response and store it in 292 // |out_public_key|. Returns false on failures. 293 bool GetPublicKey(std::string* out_public_key); 294 295 // Creates a PayloadVerifier from the zip file containing certificates. If the 296 // path to the zip file doesn't exist, falls back to use the public key. 297 // Returns a tuple with the created PayloadVerifier and if we should perform 298 // the verification. 299 std::pair<std::unique_ptr<PayloadVerifier>, bool> CreatePayloadVerifier(); 300 301 // After install_plan_ is filled with partition names and sizes, initialize 302 // metadata of partitions and map necessary devices before opening devices. 303 // Also see comment for the static PreparePartitionsForUpdate(). 304 bool PreparePartitionsForUpdate(uint64_t* required_size); 305 306 // Check if current manifest contains timestamp errors. 307 // Return: 308 // - kSuccess if update is valid. 309 // - kPayloadTimestampError if downgrade is detected 310 // - kDownloadManifestParseError if |new_version| has an incorrect format 311 // - Other error values if the source of error is known, or kError for 312 // a generic error on the device. 313 ErrorCode CheckTimestampError() const; 314 315 // Check if partition `part_name` is a dynamic partition. 316 bool IsDynamicPartition(const std::string& part_name, uint32_t slot); 317 318 // Update Engine preference store. 319 PrefsInterface* prefs_; 320 321 // BootControl and Hardware interface references. 322 BootControlInterface* boot_control_; 323 HardwareInterface* hardware_; 324 325 // The DownloadActionDelegate instance monitoring the DownloadAction, or a 326 // nullptr if not used. 327 DownloadActionDelegate* download_delegate_; 328 329 // Install Plan based on Omaha Response. 330 InstallPlan* install_plan_; 331 332 // Pointer to the current payload in install_plan_.payloads. 333 InstallPlan::Payload* payload_{nullptr}; 334 335 PayloadMetadata payload_metadata_; 336 337 // Parsed manifest. Set after enough bytes to parse the manifest were 338 // downloaded. 339 DeltaArchiveManifest manifest_; 340 bool manifest_parsed_{false}; 341 bool manifest_valid_{false}; 342 uint64_t metadata_size_{0}; 343 uint32_t metadata_signature_size_{0}; 344 uint64_t major_payload_version_{0}; 345 346 // Accumulated number of operations per partition. The i-th element is the 347 // sum of the number of operations for all the partitions from 0 to i 348 // inclusive. Valid when |manifest_valid_| is true. 349 std::vector<size_t> acc_num_operations_; 350 351 // The total operations in a payload. Valid when |manifest_valid_| is true, 352 // otherwise 0. 353 size_t num_total_operations_{0}; 354 355 // The list of partitions to update as found in the manifest major 356 // version 2. When parsing an older manifest format, the information is 357 // converted over to this format instead. 358 std::vector<PartitionUpdate> partitions_; 359 360 // Index in the list of partitions (|partitions_| member) of the current 361 // partition being processed. 362 size_t current_partition_{0}; 363 364 // Index of the next operation to perform in the manifest. The index is 365 // linear on the total number of operation on the manifest. 366 size_t next_operation_num_{0}; 367 368 // A buffer used for accumulating downloaded data. Initially, it stores the 369 // payload metadata; once that's downloaded and parsed, it stores data for 370 // the next update operation. 371 brillo::Blob buffer_; 372 // Offset of buffer_ in the binary blobs section of the update. 373 uint64_t buffer_offset_{0}; 374 375 // Last |next_operation_num_| value updated as part of the progress update. 376 uint64_t last_updated_operation_num_{std::numeric_limits<uint64_t>::max()}; 377 378 // The block size (parsed from the manifest). 379 uint32_t block_size_{0}; 380 381 // Calculates the whole payload file hash, including headers and signatures. 382 HashCalculator payload_hash_calculator_; 383 384 // Calculates the hash of the portion of the payload signed by the payload 385 // signature. This hash skips the metadata signature portion, located after 386 // the metadata and doesn't include the payload signature itself. 387 HashCalculator signed_hash_calculator_; 388 389 // Signatures message blob extracted directly from the payload. 390 std::string signatures_message_data_; 391 392 // The public key to be used. Provided as a member so that tests can 393 // override with test keys. 394 std::string public_key_path_{constants::kUpdatePayloadPublicKeyPath}; 395 396 // The path to the zip file with X509 certificates. 397 const std::string update_certificates_path_; 398 399 // The number of bytes received so far, used for progress tracking. 400 size_t total_bytes_received_{0}; 401 402 // An overall progress counter, which should reflect both download progress 403 // and the ratio of applied operations. Range is 0-100. 404 unsigned overall_progress_{0}; 405 406 // The last progress chunk recorded. 407 unsigned last_progress_chunk_{0}; 408 409 // If |true|, the update is user initiated (vs. periodic update checks). 410 bool interactive_{false}; 411 412 // The timeout after which we should force emitting a progress log 413 // (constant), and the actual point in time for the next forced log to be 414 // emitted. 415 const base::TimeDelta forced_progress_log_wait_{ 416 base::TimeDelta::FromSeconds(kProgressLogTimeoutSeconds)}; 417 base::TimeTicks forced_progress_log_time_; 418 419 // The frequency that we should write an update checkpoint (constant), and 420 // the point in time at which the next checkpoint should be written. 421 const base::TimeDelta update_checkpoint_wait_{ 422 base::TimeDelta::FromSeconds(kCheckpointFrequencySeconds)}; 423 base::TimeTicks update_checkpoint_time_; 424 425 std::unique_ptr<PartitionWriterInterface> partition_writer_; 426 427 DISALLOW_COPY_AND_ASSIGN(DeltaPerformer); 428 }; 429 430 } // namespace chromeos_update_engine 431 432 #endif // UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_ 433