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