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