1 //
2 // Copyright (C) 2015 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 #include "update_engine/payload_generator/payload_generation_config.h"
18 
19 #include <algorithm>
20 #include <map>
21 #include <utility>
22 
23 #include <base/logging.h>
24 #include <base/strings/string_number_conversions.h>
25 #include <brillo/strings/string_utils.h>
26 
27 #include "update_engine/common/utils.h"
28 #include "update_engine/payload_consumer/delta_performer.h"
29 #include "update_engine/payload_generator/boot_img_filesystem.h"
30 #include "update_engine/payload_generator/delta_diff_generator.h"
31 #include "update_engine/payload_generator/delta_diff_utils.h"
32 #include "update_engine/payload_generator/ext2_filesystem.h"
33 #include "update_engine/payload_generator/mapfile_filesystem.h"
34 #include "update_engine/payload_generator/raw_filesystem.h"
35 #include "update_engine/payload_generator/squashfs_filesystem.h"
36 
37 using std::string;
38 
39 namespace chromeos_update_engine {
40 
IsEmpty() const41 bool PostInstallConfig::IsEmpty() const {
42   return !run && path.empty() && filesystem_type.empty() && !optional;
43 }
44 
IsEmpty() const45 bool VerityConfig::IsEmpty() const {
46   return hash_tree_data_extent.num_blocks() == 0 &&
47          hash_tree_extent.num_blocks() == 0 && hash_tree_algorithm.empty() &&
48          hash_tree_salt.empty() && fec_data_extent.num_blocks() == 0 &&
49          fec_extent.num_blocks() == 0 && fec_roots == 0;
50 }
51 
ValidateExists() const52 bool PartitionConfig::ValidateExists() const {
53   TEST_AND_RETURN_FALSE(!path.empty());
54   TEST_AND_RETURN_FALSE(utils::FileExists(path.c_str()));
55   TEST_AND_RETURN_FALSE(size > 0);
56   // The requested size is within the limits of the file.
57   TEST_AND_RETURN_FALSE(static_cast<off_t>(size) <=
58                         utils::FileSize(path.c_str()));
59   return true;
60 }
61 
OpenFilesystem()62 bool PartitionConfig::OpenFilesystem() {
63   if (path.empty())
64     return true;
65   fs_interface.reset();
66   if (diff_utils::IsExtFilesystem(path)) {
67     fs_interface = Ext2Filesystem::CreateFromFile(path);
68     // TODO(deymo): The delta generator algorithm doesn't support a block size
69     // different than 4 KiB. Remove this check once that's fixed. b/26972455
70     if (fs_interface) {
71       TEST_AND_RETURN_FALSE(fs_interface->GetBlockSize() == kBlockSize);
72       return true;
73     }
74   }
75 
76   if (!mapfile_path.empty()) {
77     fs_interface = MapfileFilesystem::CreateFromFile(path, mapfile_path);
78     if (fs_interface) {
79       TEST_AND_RETURN_FALSE(fs_interface->GetBlockSize() == kBlockSize);
80       return true;
81     }
82   }
83 
84   fs_interface = BootImgFilesystem::CreateFromFile(path);
85   if (fs_interface) {
86     TEST_AND_RETURN_FALSE(fs_interface->GetBlockSize() == kBlockSize);
87     return true;
88   }
89 
90   fs_interface = SquashfsFilesystem::CreateFromFile(path,
91                                                     /*extract_deflates=*/true,
92                                                     /*load_settings=*/true);
93   if (fs_interface) {
94     TEST_AND_RETURN_FALSE(fs_interface->GetBlockSize() == kBlockSize);
95     return true;
96   }
97 
98   // Fall back to a RAW filesystem.
99   TEST_AND_RETURN_FALSE(size % kBlockSize == 0);
100   fs_interface = RawFilesystem::Create(
101       "<" + name + "-partition>", kBlockSize, size / kBlockSize);
102   return true;
103 }
104 
ValidateIsEmpty() const105 bool ImageConfig::ValidateIsEmpty() const {
106   TEST_AND_RETURN_FALSE(ImageInfoIsEmpty());
107   return partitions.empty();
108 }
109 
LoadImageSize()110 bool ImageConfig::LoadImageSize() {
111   for (PartitionConfig& part : partitions) {
112     if (part.path.empty())
113       continue;
114     part.size = utils::FileSize(part.path);
115   }
116   return true;
117 }
118 
LoadPostInstallConfig(const brillo::KeyValueStore & store)119 bool ImageConfig::LoadPostInstallConfig(const brillo::KeyValueStore& store) {
120   bool found_postinstall = false;
121   for (PartitionConfig& part : partitions) {
122     bool run_postinstall;
123     if (!store.GetBoolean("RUN_POSTINSTALL_" + part.name, &run_postinstall) ||
124         !run_postinstall)
125       continue;
126     found_postinstall = true;
127     part.postinstall.run = true;
128     store.GetString("POSTINSTALL_PATH_" + part.name, &part.postinstall.path);
129     store.GetString("FILESYSTEM_TYPE_" + part.name,
130                     &part.postinstall.filesystem_type);
131     store.GetBoolean("POSTINSTALL_OPTIONAL_" + part.name,
132                      &part.postinstall.optional);
133   }
134   if (!found_postinstall) {
135     LOG(ERROR) << "No valid postinstall config found.";
136     return false;
137   }
138   return true;
139 }
140 
LoadDynamicPartitionMetadata(const brillo::KeyValueStore & store)141 bool ImageConfig::LoadDynamicPartitionMetadata(
142     const brillo::KeyValueStore& store) {
143   auto metadata = std::make_unique<DynamicPartitionMetadata>();
144   string buf;
145   if (!store.GetString("super_partition_groups", &buf)) {
146     LOG(ERROR) << "Dynamic partition info missing super_partition_groups.";
147     return false;
148   }
149   auto group_names = brillo::string_utils::Split(buf, " ");
150   for (const auto& group_name : group_names) {
151     DynamicPartitionGroup* group = metadata->add_groups();
152     group->set_name(group_name);
153     if (!store.GetString("super_" + group_name + "_group_size", &buf) &&
154         !store.GetString(group_name + "_size", &buf)) {
155       LOG(ERROR) << "Missing super_" << group_name + "_group_size or "
156                  << group_name << "_size.";
157       return false;
158     }
159 
160     uint64_t max_size;
161     if (!base::StringToUint64(buf, &max_size)) {
162       LOG(ERROR) << "Group size for " << group_name << " = " << buf
163                  << " is not an integer.";
164       return false;
165     }
166     group->set_size(max_size);
167 
168     if (store.GetString("super_" + group_name + "_partition_list", &buf) ||
169         store.GetString(group_name + "_partition_list", &buf)) {
170       auto partition_names = brillo::string_utils::Split(buf, " ");
171       for (const auto& partition_name : partition_names) {
172         group->add_partition_names()->assign(partition_name);
173       }
174     }
175   }
176 
177   bool snapshot_enabled = false;
178   store.GetBoolean("virtual_ab", &snapshot_enabled);
179   metadata->set_snapshot_enabled(snapshot_enabled);
180 
181   dynamic_partition_metadata = std::move(metadata);
182   return true;
183 }
184 
ValidateDynamicPartitionMetadata() const185 bool ImageConfig::ValidateDynamicPartitionMetadata() const {
186   if (dynamic_partition_metadata == nullptr) {
187     LOG(ERROR) << "dynamic_partition_metadata is not loaded.";
188     return false;
189   }
190 
191   for (const auto& group : dynamic_partition_metadata->groups()) {
192     uint64_t sum_size = 0;
193     for (const auto& partition_name : group.partition_names()) {
194       auto partition_config = std::find_if(partitions.begin(),
195                                            partitions.end(),
196                                            [&partition_name](const auto& e) {
197                                              return e.name == partition_name;
198                                            });
199 
200       if (partition_config == partitions.end()) {
201         LOG(ERROR) << "Cannot find partition " << partition_name
202                    << " which is in " << group.name() << "_partition_list";
203         return false;
204       }
205       sum_size += partition_config->size;
206     }
207 
208     if (sum_size > group.size()) {
209       LOG(ERROR) << "Sum of sizes in " << group.name() << "_partition_list is "
210                  << sum_size << ", which is greater than " << group.name()
211                  << "_size (" << group.size() << ")";
212       return false;
213     }
214   }
215   return true;
216 }
217 
ImageInfoIsEmpty() const218 bool ImageConfig::ImageInfoIsEmpty() const {
219   return image_info.board().empty() && image_info.key().empty() &&
220          image_info.channel().empty() && image_info.version().empty() &&
221          image_info.build_channel().empty() &&
222          image_info.build_version().empty();
223 }
224 
PayloadVersion(uint64_t major_version,uint32_t minor_version)225 PayloadVersion::PayloadVersion(uint64_t major_version, uint32_t minor_version) {
226   major = major_version;
227   minor = minor_version;
228 }
229 
Validate() const230 bool PayloadVersion::Validate() const {
231   TEST_AND_RETURN_FALSE(major == kBrilloMajorPayloadVersion);
232   TEST_AND_RETURN_FALSE(minor == kFullPayloadMinorVersion ||
233                         minor == kSourceMinorPayloadVersion ||
234                         minor == kOpSrcHashMinorPayloadVersion ||
235                         minor == kBrotliBsdiffMinorPayloadVersion ||
236                         minor == kPuffdiffMinorPayloadVersion ||
237                         minor == kVerityMinorPayloadVersion ||
238                         minor == kPartialUpdateMinorPayloadVersion);
239   return true;
240 }
241 
OperationAllowed(InstallOperation::Type operation) const242 bool PayloadVersion::OperationAllowed(InstallOperation::Type operation) const {
243   switch (operation) {
244     // Full operations:
245     case InstallOperation::REPLACE:
246     case InstallOperation::REPLACE_BZ:
247       // These operations were included in the original payload format.
248     case InstallOperation::REPLACE_XZ:
249       // These operations are included minor version 3 or newer and full
250       // payloads.
251       return true;
252 
253     case InstallOperation::ZERO:
254     case InstallOperation::DISCARD:
255       // The implementation of these operations had a bug in earlier versions
256       // that prevents them from being used in any payload. We will enable
257       // them for delta payloads for now.
258       return minor >= kBrotliBsdiffMinorPayloadVersion;
259 
260     case InstallOperation::SOURCE_COPY:
261     case InstallOperation::SOURCE_BSDIFF:
262       return minor >= kSourceMinorPayloadVersion;
263 
264     case InstallOperation::BROTLI_BSDIFF:
265       return minor >= kBrotliBsdiffMinorPayloadVersion;
266 
267     case InstallOperation::PUFFDIFF:
268       return minor >= kPuffdiffMinorPayloadVersion;
269 
270     case InstallOperation::MOVE:
271     case InstallOperation::BSDIFF:
272       NOTREACHED();
273   }
274   return false;
275 }
276 
IsDeltaOrPartial() const277 bool PayloadVersion::IsDeltaOrPartial() const {
278   return minor != kFullPayloadMinorVersion;
279 }
280 
Validate() const281 bool PayloadGenerationConfig::Validate() const {
282   TEST_AND_RETURN_FALSE(version.Validate());
283   TEST_AND_RETURN_FALSE(version.IsDeltaOrPartial() ==
284                         (is_delta || is_partial_update));
285   if (is_delta) {
286     for (const PartitionConfig& part : source.partitions) {
287       if (!part.path.empty()) {
288         TEST_AND_RETURN_FALSE(part.ValidateExists());
289         TEST_AND_RETURN_FALSE(part.size % block_size == 0);
290       }
291       // Source partition should not have postinstall or verity config.
292       TEST_AND_RETURN_FALSE(part.postinstall.IsEmpty());
293       TEST_AND_RETURN_FALSE(part.verity.IsEmpty());
294     }
295 
296     // If new_image_info is present, old_image_info must be present.
297     TEST_AND_RETURN_FALSE(source.ImageInfoIsEmpty() ==
298                           target.ImageInfoIsEmpty());
299   } else {
300     // All the "source" image fields must be empty for full payloads.
301     TEST_AND_RETURN_FALSE(source.ValidateIsEmpty());
302   }
303 
304   // In all cases, the target image must exists.
305   for (const PartitionConfig& part : target.partitions) {
306     TEST_AND_RETURN_FALSE(part.ValidateExists());
307     TEST_AND_RETURN_FALSE(part.size % block_size == 0);
308     if (version.minor < kVerityMinorPayloadVersion)
309       TEST_AND_RETURN_FALSE(part.verity.IsEmpty());
310   }
311 
312   if (version.minor < kPartialUpdateMinorPayloadVersion) {
313     TEST_AND_RETURN_FALSE(!is_partial_update);
314   }
315 
316   TEST_AND_RETURN_FALSE(hard_chunk_size == -1 ||
317                         hard_chunk_size % block_size == 0);
318   TEST_AND_RETURN_FALSE(soft_chunk_size % block_size == 0);
319 
320   TEST_AND_RETURN_FALSE(rootfs_partition_size % block_size == 0);
321 
322   return true;
323 }
324 
325 }  // namespace chromeos_update_engine
326