• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2020 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 #include <update_engine/payload_consumer/partition_writer.h>
17 
18 #include <fcntl.h>
19 #include <linux/fs.h>
20 #include <sys/mman.h>
21 
22 #include <inttypes.h>
23 
24 #include <algorithm>
25 #include <initializer_list>
26 #include <memory>
27 #include <string>
28 #include <utility>
29 #include <vector>
30 
31 #include <base/strings/string_number_conversions.h>
32 #include <base/strings/string_util.h>
33 #include <base/strings/stringprintf.h>
34 
35 #include "update_engine/common/terminator.h"
36 #include "update_engine/common/utils.h"
37 #include "update_engine/payload_consumer/bzip_extent_writer.h"
38 #include "update_engine/payload_consumer/cached_file_descriptor.h"
39 #include "update_engine/payload_consumer/extent_reader.h"
40 #include "update_engine/payload_consumer/extent_writer.h"
41 #include "update_engine/payload_consumer/file_descriptor_utils.h"
42 #include "update_engine/payload_consumer/install_operation_executor.h"
43 #include "update_engine/payload_consumer/install_plan.h"
44 #include "update_engine/payload_consumer/mount_history.h"
45 #include "update_engine/payload_consumer/payload_constants.h"
46 #include "update_engine/payload_consumer/xz_extent_writer.h"
47 #include "update_engine/payload_generator/extent_utils.h"
48 
49 namespace chromeos_update_engine {
50 
51 namespace {
52 constexpr uint64_t kCacheSize = 1024 * 1024;  // 1MB
53 
54 // Discard the tail of the block device referenced by |fd|, from the offset
55 // |data_size| until the end of the block device. Returns whether the data was
56 // discarded.
57 
DiscardPartitionTail(const FileDescriptorPtr & fd,uint64_t data_size)58 bool DiscardPartitionTail(const FileDescriptorPtr& fd, uint64_t data_size) {
59   uint64_t part_size = fd->BlockDevSize();
60   if (!part_size || part_size <= data_size)
61     return false;
62 
63   struct blkioctl_request {
64     int number;
65     const char* name;
66   };
67   const std::initializer_list<blkioctl_request> blkioctl_requests = {
68       {BLKDISCARD, "BLKDISCARD"},
69       {BLKSECDISCARD, "BLKSECDISCARD"},
70 #ifdef BLKZEROOUT
71       {BLKZEROOUT, "BLKZEROOUT"},
72 #endif
73   };
74   for (const auto& req : blkioctl_requests) {
75     int error = 0;
76     if (fd->BlkIoctl(req.number, data_size, part_size - data_size, &error) &&
77         error == 0) {
78       return true;
79     }
80     LOG(WARNING) << "Error discarding the last "
81                  << (part_size - data_size) / 1024 << " KiB using ioctl("
82                  << req.name << ")";
83   }
84   return false;
85 }
86 
87 }  // namespace
88 
89 // Opens path for read/write. On success returns an open FileDescriptor
90 // and sets *err to 0. On failure, sets *err to errno and returns nullptr.
OpenFile(const char * path,int mode,bool cache_writes,int * err)91 FileDescriptorPtr OpenFile(const char* path,
92                            int mode,
93                            bool cache_writes,
94                            int* err) {
95   // Try to mark the block device read-only based on the mode. Ignore any
96   // failure since this won't work when passing regular files.
97   bool read_only = (mode & O_ACCMODE) == O_RDONLY;
98   utils::SetBlockDeviceReadOnly(path, read_only);
99 
100   FileDescriptorPtr fd(new EintrSafeFileDescriptor());
101   if (cache_writes && !read_only) {
102     fd = FileDescriptorPtr(new CachedFileDescriptor(fd, kCacheSize));
103     LOG(INFO) << "Caching writes.";
104   }
105   if (!fd->Open(path, mode, 000)) {
106     *err = errno;
107     PLOG(ERROR) << "Unable to open file " << path;
108     return nullptr;
109   }
110   *err = 0;
111   return fd;
112 }
113 
PartitionWriter(const PartitionUpdate & partition_update,const InstallPlan::Partition & install_part,DynamicPartitionControlInterface * dynamic_control,size_t block_size,bool is_interactive)114 PartitionWriter::PartitionWriter(
115     const PartitionUpdate& partition_update,
116     const InstallPlan::Partition& install_part,
117     DynamicPartitionControlInterface* dynamic_control,
118     size_t block_size,
119     bool is_interactive)
120     : partition_update_(partition_update),
121       install_part_(install_part),
122       dynamic_control_(dynamic_control),
123       verified_source_fd_(block_size, install_part.source_path),
124       interactive_(is_interactive),
125       block_size_(block_size),
126       install_op_executor_(block_size) {}
127 
~PartitionWriter()128 PartitionWriter::~PartitionWriter() {
129   Close();
130 }
131 
OpenSourcePartition(uint32_t source_slot,bool source_may_exist)132 bool PartitionWriter::OpenSourcePartition(uint32_t source_slot,
133                                           bool source_may_exist) {
134   source_path_.clear();
135   if (!source_may_exist) {
136     return true;
137   }
138   if (install_part_.source_size > 0 && !install_part_.source_path.empty()) {
139     source_path_ = install_part_.source_path;
140     if (!verified_source_fd_.Open()) {
141       LOG(ERROR) << "Unable to open source partition " << install_part_.name
142                  << " on slot " << BootControlInterface::SlotName(source_slot)
143                  << ", file " << source_path_;
144       return false;
145     }
146   }
147   return true;
148 }
149 
Init(const InstallPlan * install_plan,bool source_may_exist,size_t next_op_index)150 bool PartitionWriter::Init(const InstallPlan* install_plan,
151                            bool source_may_exist,
152                            size_t next_op_index) {
153   const PartitionUpdate& partition = partition_update_;
154   uint32_t source_slot = install_plan->source_slot;
155   uint32_t target_slot = install_plan->target_slot;
156   TEST_AND_RETURN_FALSE(OpenSourcePartition(source_slot, source_may_exist));
157 
158   // We shouldn't open the source partition in certain cases, e.g. some dynamic
159   // partitions in delta payload, partitions included in the full payload for
160   // partial updates. Use the source size as the indicator.
161 
162   target_path_ = install_part_.target_path;
163   int err;
164 
165   int flags = O_RDWR;
166   if (!interactive_)
167     flags |= O_DSYNC;
168 
169   LOG(INFO) << "Opening " << target_path_ << " partition with"
170             << (interactive_ ? "out" : "") << " O_DSYNC";
171 
172   target_fd_ = OpenFile(target_path_.c_str(), flags, true, &err);
173   if (!target_fd_) {
174     LOG(ERROR) << "Unable to open target partition "
175                << partition.partition_name() << " on slot "
176                << BootControlInterface::SlotName(target_slot) << ", file "
177                << target_path_;
178     return false;
179   }
180 
181   LOG(INFO) << "Applying " << partition.operations().size()
182             << " operations to partition \"" << partition.partition_name()
183             << "\"";
184 
185   // Discard the end of the partition, but ignore failures.
186   DiscardPartitionTail(target_fd_, install_part_.target_size);
187 
188   return true;
189 }
190 
PerformReplaceOperation(const InstallOperation & operation,const void * data,size_t count)191 bool PartitionWriter::PerformReplaceOperation(const InstallOperation& operation,
192                                               const void* data,
193                                               size_t count) {
194   // Setup the ExtentWriter stack based on the operation type.
195   std::unique_ptr<ExtentWriter> writer = CreateBaseExtentWriter();
196   return install_op_executor_.ExecuteReplaceOperation(
197       operation, std::move(writer), data, count);
198 }
199 
PerformZeroOrDiscardOperation(const InstallOperation & operation)200 bool PartitionWriter::PerformZeroOrDiscardOperation(
201     const InstallOperation& operation) {
202 #ifdef BLKZEROOUT
203   int request =
204       (operation.type() == InstallOperation::ZERO ? BLKZEROOUT : BLKDISCARD);
205 #else   // !defined(BLKZEROOUT)
206   auto writer = CreateBaseExtentWriter();
207   return install_op_executor_.ExecuteZeroOrDiscardOperation(operation,
208                                                             writer.get());
209 #endif  // !defined(BLKZEROOUT)
210 
211   for (const Extent& extent : operation.dst_extents()) {
212     const uint64_t start = extent.start_block() * block_size_;
213     const uint64_t length = extent.num_blocks() * block_size_;
214     int result = 0;
215     if (target_fd_->BlkIoctl(request, start, length, &result) && result == 0) {
216       continue;
217     }
218     // In case of failure, we fall back to writing 0 for the entire operation.
219     PLOG(WARNING) << "BlkIoctl failed. Falling back to write 0s for remainder "
220                      "of this operation.";
221     auto writer = CreateBaseExtentWriter();
222     return install_op_executor_.ExecuteZeroOrDiscardOperation(
223         operation, std::move(writer));
224   }
225   return true;
226 }
227 
PerformSourceCopyOperation(const InstallOperation & operation,ErrorCode * error)228 bool PartitionWriter::PerformSourceCopyOperation(
229     const InstallOperation& operation, ErrorCode* error) {
230   // The device may optimize the SOURCE_COPY operation.
231   // Being this a device-specific optimization let DynamicPartitionController
232   // decide it the operation should be skipped.
233   const PartitionUpdate& partition = partition_update_;
234 
235   InstallOperation buf;
236   const bool should_optimize = dynamic_control_->OptimizeOperation(
237       partition.partition_name(), operation, &buf);
238   const InstallOperation& optimized = should_optimize ? buf : operation;
239 
240   // Invoke ChooseSourceFD with original operation, so that it can properly
241   // verify source hashes. Optimized operation might contain a smaller set of
242   // extents, or completely empty.
243   auto source_fd = ChooseSourceFD(operation, error);
244   if (source_fd == nullptr) {
245     LOG(ERROR) << "Unrecoverable source hash mismatch found on partition "
246                << partition.partition_name()
247                << " extents: " << ExtentsToString(operation.src_extents());
248     return false;
249   }
250 
251   auto writer = CreateBaseExtentWriter();
252   return install_op_executor_.ExecuteSourceCopyOperation(
253       optimized, std::move(writer), source_fd);
254 }
255 
PerformDiffOperation(const InstallOperation & operation,ErrorCode * error,const void * data,size_t count)256 bool PartitionWriter::PerformDiffOperation(const InstallOperation& operation,
257                                            ErrorCode* error,
258                                            const void* data,
259                                            size_t count) {
260   FileDescriptorPtr source_fd = ChooseSourceFD(operation, error);
261   TEST_AND_RETURN_FALSE(source_fd != nullptr);
262 
263   auto writer = CreateBaseExtentWriter();
264   return install_op_executor_.ExecuteDiffOperation(
265       operation, std::move(writer), source_fd, data, count);
266 }
267 
ChooseSourceFD(const InstallOperation & operation,ErrorCode * error)268 FileDescriptorPtr PartitionWriter::ChooseSourceFD(
269     const InstallOperation& operation, ErrorCode* error) {
270   return verified_source_fd_.ChooseSourceFD(operation, error);
271 }
272 
Close()273 int PartitionWriter::Close() {
274   int err = 0;
275 
276   source_path_.clear();
277 
278   if (target_fd_ && !target_fd_->Close()) {
279     err = errno;
280     PLOG(ERROR) << "Error closing target partition";
281     if (!err)
282       err = 1;
283   }
284   target_fd_.reset();
285   target_path_.clear();
286 
287   return -err;
288 }
289 
CheckpointUpdateProgress(size_t next_op_index)290 void PartitionWriter::CheckpointUpdateProgress(size_t next_op_index) {
291   target_fd_->Flush();
292 }
293 
CreateBaseExtentWriter()294 std::unique_ptr<ExtentWriter> PartitionWriter::CreateBaseExtentWriter() {
295   return std::make_unique<DirectExtentWriter>(target_fd_);
296 }
297 
ValidateSourceHash(const InstallOperation & operation,const FileDescriptorPtr source_fd,size_t block_size,ErrorCode * error)298 bool PartitionWriter::ValidateSourceHash(const InstallOperation& operation,
299                                          const FileDescriptorPtr source_fd,
300                                          size_t block_size,
301                                          ErrorCode* error) {
302   brillo::Blob source_hash;
303   TEST_AND_RETURN_FALSE_ERRNO(fd_utils::ReadAndHashExtents(
304       source_fd, operation.src_extents(), block_size, &source_hash));
305   return ValidateSourceHash(source_hash, operation, source_fd, error);
306 }
307 
ValidateSourceHash(const brillo::Blob & calculated_hash,const InstallOperation & operation,const FileDescriptorPtr source_fd,ErrorCode * error)308 bool PartitionWriter::ValidateSourceHash(const brillo::Blob& calculated_hash,
309                                          const InstallOperation& operation,
310                                          const FileDescriptorPtr source_fd,
311                                          ErrorCode* error) {
312   using std::string;
313   using std::vector;
314   brillo::Blob expected_source_hash(operation.src_sha256_hash().begin(),
315                                     operation.src_sha256_hash().end());
316   if (calculated_hash != expected_source_hash) {
317     LOG(ERROR) << "The hash of the source data on disk for this operation "
318                << "doesn't match the expected value. This could mean that the "
319                << "delta update payload was targeted for another version, or "
320                << "that the source partition was modified after it was "
321                << "installed, for example, by mounting a filesystem.";
322     LOG(ERROR) << "Expected:   sha256|hex = "
323                << base::HexEncode(expected_source_hash.data(),
324                                   expected_source_hash.size());
325     LOG(ERROR) << "Calculated: sha256|hex = "
326                << base::HexEncode(calculated_hash.data(),
327                                   calculated_hash.size());
328 
329     vector<string> source_extents;
330     for (const Extent& ext : operation.src_extents()) {
331       source_extents.push_back(
332           base::StringPrintf("%" PRIu64 ":%" PRIu64,
333                              static_cast<uint64_t>(ext.start_block()),
334                              static_cast<uint64_t>(ext.num_blocks())));
335     }
336     LOG(ERROR) << "Operation source (offset:size) in blocks: "
337                << base::JoinString(source_extents, ",");
338 
339     // Log remount history if this device is an ext4 partition.
340     LogMountHistory(source_fd);
341 
342     *error = ErrorCode::kDownloadStateInitializationError;
343     return false;
344   }
345   return true;
346 }
347 
348 }  // namespace chromeos_update_engine
349