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/payload_metadata.h" 39 #include "update_engine/payload_consumer/payload_verifier.h" 40 #include "update_engine/update_metadata.pb.h" 41 42 namespace chromeos_update_engine { 43 44 class DownloadActionDelegate; 45 class BootControlInterface; 46 class HardwareInterface; 47 class PrefsInterface; 48 49 // This class performs the actions in a delta update synchronously. The delta 50 // update itself should be passed in in chunks as it is received. 51 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 DeltaPerformer(PrefsInterface * prefs,BootControlInterface * boot_control,HardwareInterface * hardware,DownloadActionDelegate * download_delegate,InstallPlan * install_plan,InstallPlan::Payload * payload,bool interactive)68 DeltaPerformer(PrefsInterface* prefs, 69 BootControlInterface* boot_control, 70 HardwareInterface* hardware, 71 DownloadActionDelegate* download_delegate, 72 InstallPlan* install_plan, 73 InstallPlan::Payload* payload, 74 bool interactive) 75 : prefs_(prefs), 76 boot_control_(boot_control), 77 hardware_(hardware), 78 download_delegate_(download_delegate), 79 install_plan_(install_plan), 80 payload_(payload), 81 interactive_(interactive) { 82 CHECK(install_plan_); 83 } 84 85 // FileWriter's Write implementation where caller doesn't care about 86 // error codes. Write(const void * bytes,size_t count)87 bool Write(const void* bytes, size_t count) override { 88 ErrorCode error; 89 return Write(bytes, count, &error); 90 } 91 92 // FileWriter's Write implementation that returns a more specific |error| code 93 // in case of failures in Write operation. 94 bool Write(const void* bytes, size_t count, ErrorCode* error) override; 95 96 // Wrapper around close. Returns 0 on success or -errno on error. 97 // Closes both 'path' given to Open() and the kernel path. 98 int Close() override; 99 100 // Open the target and source (if delta payload) file descriptors for the 101 // |current_partition_|. The manifest needs to be already parsed for this to 102 // work. Returns whether the required file descriptors were successfully open. 103 bool OpenCurrentPartition(); 104 105 // Attempt to open the error-corrected device for the current partition. 106 // Returns whether the operation succeeded. 107 bool OpenCurrentECCPartition(); 108 109 // Closes the current partition file descriptors if open. Returns 0 on success 110 // or -errno on error. 111 int CloseCurrentPartition(); 112 113 // Returns |true| only if the manifest has been processed and it's valid. 114 bool IsManifestValid(); 115 116 // Verifies the downloaded payload against the signed hash included in the 117 // payload, against the update check hash and size using the public key and 118 // returns ErrorCode::kSuccess on success, an error code on failure. 119 // This method should be called after closing the stream. Note this method 120 // skips the signed hash check if the public key is unavailable; it returns 121 // ErrorCode::kSignedDeltaPayloadExpectedError if the public key is available 122 // but the delta payload doesn't include a signature. 123 ErrorCode VerifyPayload(const brillo::Blob& update_check_response_hash, 124 const uint64_t update_check_response_size); 125 126 // Converts an ordered collection of Extent objects which contain data of 127 // length full_length to a comma-separated string. For each Extent, the 128 // string will have the start offset and then the length in bytes. 129 // The length value of the last extent in the string may be short, since 130 // the full length of all extents in the string is capped to full_length. 131 // Also, an extent starting at kSparseHole, appears as -1 in the string. 132 // For example, if the Extents are {1, 1}, {4, 2}, {kSparseHole, 1}, 133 // {0, 1}, block_size is 4096, and full_length is 5 * block_size - 13, 134 // the resulting string will be: "4096:4096,16384:8192,-1:4096,0:4083" 135 static bool ExtentsToBsdiffPositionsString( 136 const google::protobuf::RepeatedPtrField<Extent>& extents, 137 uint64_t block_size, 138 uint64_t full_length, 139 std::string* positions_string); 140 141 // Returns true if a previous update attempt can be continued based on the 142 // persistent preferences and the new update check response hash. 143 static bool CanResumeUpdate(PrefsInterface* prefs, 144 const std::string& update_check_response_hash); 145 146 // Resets the persistent update progress state to indicate that an update 147 // can't be resumed. Performs a quick update-in-progress reset if |quick| is 148 // true, otherwise resets all progress-related update state. 149 // If |skip_dynamic_partititon_metadata_updated| is true, do not reset 150 // dynamic-partition-metadata-updated. 151 // Returns true on success, false otherwise. 152 static bool ResetUpdateProgress( 153 PrefsInterface* prefs, 154 bool quick, 155 bool skip_dynamic_partititon_metadata_updated = false); 156 157 // Attempts to parse the update metadata starting from the beginning of 158 // |payload|. On success, returns kMetadataParseSuccess. Returns 159 // kMetadataParseInsufficientData if more data is needed to parse the complete 160 // metadata. Returns kMetadataParseError if the metadata can't be parsed given 161 // the payload. 162 MetadataParseResult ParsePayloadMetadata(const brillo::Blob& payload, 163 ErrorCode* error); 164 set_public_key_path(const std::string & public_key_path)165 void set_public_key_path(const std::string& public_key_path) { 166 public_key_path_ = public_key_path; 167 } 168 set_update_certificates_path(const std::string & update_certificates_path)169 void set_update_certificates_path( 170 const std::string& update_certificates_path) { 171 update_certificates_path_ = update_certificates_path; 172 } 173 174 // Return true if header parsing is finished and no errors occurred. 175 bool IsHeaderParsed() const; 176 177 // Returns the delta minor version. If this value is defined in the manifest, 178 // it returns that value, otherwise it returns the default value. 179 uint32_t GetMinorVersion() const; 180 181 // Compare |calculated_hash| with source hash in |operation|, return false and 182 // dump hash and set |error| if don't match. 183 // |source_fd| is the file descriptor of the source partition. 184 static bool ValidateSourceHash(const brillo::Blob& calculated_hash, 185 const InstallOperation& operation, 186 const FileDescriptorPtr source_fd, 187 ErrorCode* error); 188 189 // Initialize partitions and allocate required space for an update with the 190 // given |manifest|. |update_check_response_hash| is used to check if the 191 // previous call to this function corresponds to the same payload. 192 // - Same payload: not make any persistent modifications (not write to disk) 193 // - Different payload: make persistent modifications (write to disk) 194 // In both cases, in-memory flags are updated. This function must be called 195 // on the payload at least once (to update in-memory flags) before writing 196 // (applying) the payload. 197 // If error due to insufficient space, |required_size| is set to the required 198 // size on the device to apply the payload. 199 static bool PreparePartitionsForUpdate( 200 PrefsInterface* prefs, 201 BootControlInterface* boot_control, 202 BootControlInterface::Slot target_slot, 203 const DeltaArchiveManifest& manifest, 204 const std::string& update_check_response_hash, 205 uint64_t* required_size); 206 207 private: 208 friend class DeltaPerformerTest; 209 friend class DeltaPerformerIntegrationTest; 210 FRIEND_TEST(DeltaPerformerTest, BrilloMetadataSignatureSizeTest); 211 FRIEND_TEST(DeltaPerformerTest, BrilloParsePayloadMetadataTest); 212 FRIEND_TEST(DeltaPerformerTest, ChooseSourceFDTest); 213 FRIEND_TEST(DeltaPerformerTest, UsePublicKeyFromResponse); 214 215 // Parse and move the update instructions of all partitions into our local 216 // |partitions_| variable based on the version of the payload. Requires the 217 // manifest to be parsed and valid. 218 bool ParseManifestPartitions(ErrorCode* error); 219 220 // Appends up to |*count_p| bytes from |*bytes_p| to |buffer_|, but only to 221 // the extent that the size of |buffer_| does not exceed |max|. Advances 222 // |*cbytes_p| and decreases |*count_p| by the actual number of bytes copied, 223 // and returns this number. 224 size_t CopyDataToBuffer(const char** bytes_p, size_t* count_p, size_t max); 225 226 // If |op_result| is false, emits an error message using |op_type_name| and 227 // sets |*error| accordingly. Otherwise does nothing. Returns |op_result|. 228 bool HandleOpResult(bool op_result, 229 const char* op_type_name, 230 ErrorCode* error); 231 232 // Logs the progress of downloading/applying an update. 233 void LogProgress(const char* message_prefix); 234 235 // Update overall progress metrics, log as necessary. 236 void UpdateOverallProgress(bool force_log, const char* message_prefix); 237 238 // Returns true if enough of the delta file has been passed via Write() 239 // to be able to perform a given install operation. 240 bool CanPerformInstallOperation(const InstallOperation& operation); 241 242 // Checks the integrity of the payload manifest. Returns true upon success, 243 // false otherwise. 244 ErrorCode ValidateManifest(); 245 246 // Validates that the hash of the blobs corresponding to the given |operation| 247 // matches what's specified in the manifest in the payload. 248 // Returns ErrorCode::kSuccess on match or a suitable error code otherwise. 249 ErrorCode ValidateOperationHash(const InstallOperation& operation); 250 251 // Returns true on success. 252 bool PerformInstallOperation(const InstallOperation& operation); 253 254 // These perform a specific type of operation and return true on success. 255 // |error| will be set if source hash mismatch, otherwise |error| might not be 256 // set even if it fails. 257 bool PerformReplaceOperation(const InstallOperation& operation); 258 bool PerformZeroOrDiscardOperation(const InstallOperation& operation); 259 bool PerformSourceCopyOperation(const InstallOperation& operation, 260 ErrorCode* error); 261 bool PerformSourceBsdiffOperation(const InstallOperation& operation, 262 ErrorCode* error); 263 bool PerformPuffDiffOperation(const InstallOperation& operation, 264 ErrorCode* error); 265 266 // For a given operation, choose the source fd to be used (raw device or error 267 // correction device) based on the source operation hash. 268 // Returns nullptr if the source hash mismatch cannot be corrected, and set 269 // the |error| accordingly. 270 FileDescriptorPtr ChooseSourceFD(const InstallOperation& operation, 271 ErrorCode* error); 272 273 // Extracts the payload signature message from the current |buffer_| if the 274 // offset matches the one specified by the manifest. Returns whether the 275 // signature was extracted. 276 bool ExtractSignatureMessage(); 277 278 // Updates the payload hash calculator with the bytes in |buffer_|, also 279 // updates the signed hash calculator with the first |signed_hash_buffer_size| 280 // bytes in |buffer_|. Then discard the content, ensuring that memory is being 281 // deallocated. If |do_advance_offset|, advances the internal offset counter 282 // accordingly. 283 void DiscardBuffer(bool do_advance_offset, size_t signed_hash_buffer_size); 284 285 // Checkpoints the update progress into persistent storage to allow this 286 // update attempt to be resumed after reboot. 287 // If |force| is false, checkpoint may be throttled. 288 bool CheckpointUpdateProgress(bool force); 289 290 // Primes the required update state. Returns true if the update state was 291 // successfully initialized to a saved resume state or if the update is a new 292 // update. Returns false otherwise. 293 bool PrimeUpdateState(); 294 295 // Get the public key to be used to verify metadata signature or payload 296 // signature. Always use |public_key_path_| if exists, otherwise if the Omaha 297 // response contains a public RSA key and we're allowed to use it (e.g. if 298 // we're in developer mode), decode the key from the response and store it in 299 // |out_public_key|. Returns false on failures. 300 bool GetPublicKey(std::string* out_public_key); 301 302 // Creates a PayloadVerifier from the zip file containing certificates. If the 303 // path to the zip file doesn't exist, falls back to use the public key. 304 // Returns a tuple with the created PayloadVerifier and if we should perform 305 // the verification. 306 std::pair<std::unique_ptr<PayloadVerifier>, bool> CreatePayloadVerifier(); 307 308 // After install_plan_ is filled with partition names and sizes, initialize 309 // metadata of partitions and map necessary devices before opening devices. 310 // Also see comment for the static PreparePartitionsForUpdate(). 311 bool PreparePartitionsForUpdate(uint64_t* required_size); 312 313 // Update Engine preference store. 314 PrefsInterface* prefs_; 315 316 // BootControl and Hardware interface references. 317 BootControlInterface* boot_control_; 318 HardwareInterface* hardware_; 319 320 // The DownloadActionDelegate instance monitoring the DownloadAction, or a 321 // nullptr if not used. 322 DownloadActionDelegate* download_delegate_; 323 324 // Install Plan based on Omaha Response. 325 InstallPlan* install_plan_; 326 327 // Pointer to the current payload in install_plan_.payloads. 328 InstallPlan::Payload* payload_{nullptr}; 329 330 // File descriptor of the source partition. Only set while updating a 331 // partition when using a delta payload. 332 FileDescriptorPtr source_fd_{nullptr}; 333 334 // File descriptor of the error corrected source partition. Only set while 335 // updating partition using a delta payload for a partition where error 336 // correction is available. The size of the error corrected device is smaller 337 // than the underlying raw device, since it doesn't include the error 338 // correction blocks. 339 FileDescriptorPtr source_ecc_fd_{nullptr}; 340 341 // The total number of operations that failed source hash verification but 342 // passed after falling back to the error-corrected |source_ecc_fd_| device. 343 uint64_t source_ecc_recovered_failures_{0}; 344 345 // Whether opening the current partition as an error-corrected device failed. 346 // Used to avoid re-opening the same source partition if it is not actually 347 // error corrected. 348 bool source_ecc_open_failure_{false}; 349 350 // File descriptor of the target partition. Only set while performing the 351 // operations of a given partition. 352 FileDescriptorPtr target_fd_{nullptr}; 353 354 // Paths the |source_fd_| and |target_fd_| refer to. 355 std::string source_path_; 356 std::string target_path_; 357 358 PayloadMetadata payload_metadata_; 359 360 // Parsed manifest. Set after enough bytes to parse the manifest were 361 // downloaded. 362 DeltaArchiveManifest manifest_; 363 bool manifest_parsed_{false}; 364 bool manifest_valid_{false}; 365 uint64_t metadata_size_{0}; 366 uint32_t metadata_signature_size_{0}; 367 uint64_t major_payload_version_{0}; 368 369 // Accumulated number of operations per partition. The i-th element is the 370 // sum of the number of operations for all the partitions from 0 to i 371 // inclusive. Valid when |manifest_valid_| is true. 372 std::vector<size_t> acc_num_operations_; 373 374 // The total operations in a payload. Valid when |manifest_valid_| is true, 375 // otherwise 0. 376 size_t num_total_operations_{0}; 377 378 // The list of partitions to update as found in the manifest major version 2. 379 // When parsing an older manifest format, the information is converted over to 380 // this format instead. 381 std::vector<PartitionUpdate> partitions_; 382 383 // Index in the list of partitions (|partitions_| member) of the current 384 // partition being processed. 385 size_t current_partition_{0}; 386 387 // Index of the next operation to perform in the manifest. The index is linear 388 // on the total number of operation on the manifest. 389 size_t next_operation_num_{0}; 390 391 // A buffer used for accumulating downloaded data. Initially, it stores the 392 // payload metadata; once that's downloaded and parsed, it stores data for the 393 // next update operation. 394 brillo::Blob buffer_; 395 // Offset of buffer_ in the binary blobs section of the update. 396 uint64_t buffer_offset_{0}; 397 398 // Last |buffer_offset_| value updated as part of the progress update. 399 uint64_t last_updated_buffer_offset_{std::numeric_limits<uint64_t>::max()}; 400 401 // The block size (parsed from the manifest). 402 uint32_t block_size_{0}; 403 404 // Calculates the whole payload file hash, including headers and signatures. 405 HashCalculator payload_hash_calculator_; 406 407 // Calculates the hash of the portion of the payload signed by the payload 408 // signature. This hash skips the metadata signature portion, located after 409 // the metadata and doesn't include the payload signature itself. 410 HashCalculator signed_hash_calculator_; 411 412 // Signatures message blob extracted directly from the payload. 413 std::string signatures_message_data_; 414 415 // The public key to be used. Provided as a member so that tests can 416 // override with test keys. 417 std::string public_key_path_{constants::kUpdatePayloadPublicKeyPath}; 418 419 // The path to the zip file with X509 certificates. 420 std::string update_certificates_path_{constants::kUpdateCertificatesPath}; 421 422 // The number of bytes received so far, used for progress tracking. 423 size_t total_bytes_received_{0}; 424 425 // An overall progress counter, which should reflect both download progress 426 // and the ratio of applied operations. Range is 0-100. 427 unsigned overall_progress_{0}; 428 429 // The last progress chunk recorded. 430 unsigned last_progress_chunk_{0}; 431 432 // If |true|, the update is user initiated (vs. periodic update checks). 433 bool interactive_{false}; 434 435 // The timeout after which we should force emitting a progress log (constant), 436 // and the actual point in time for the next forced log to be emitted. 437 const base::TimeDelta forced_progress_log_wait_{ 438 base::TimeDelta::FromSeconds(kProgressLogTimeoutSeconds)}; 439 base::TimeTicks forced_progress_log_time_; 440 441 // The frequency that we should write an update checkpoint (constant), and 442 // the point in time at which the next checkpoint should be written. 443 const base::TimeDelta update_checkpoint_wait_{ 444 base::TimeDelta::FromSeconds(kCheckpointFrequencySeconds)}; 445 base::TimeTicks update_checkpoint_time_; 446 447 DISALLOW_COPY_AND_ASSIGN(DeltaPerformer); 448 }; 449 450 } // namespace chromeos_update_engine 451 452 #endif // UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_ 453