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