blob: 9838794981ba770dbfbae4514122cab871502e6a [file] [log] [blame]
Amin Hassanid7da8f42017-08-23 14:29:40 -07001//
2// Copyright (C) 2017 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/squashfs_filesystem.h"
18
19#include <fcntl.h>
20
21#include <algorithm>
22#include <string>
Amin Hassani3cd4df12017-08-25 11:21:53 -070023#include <utility>
Amin Hassanid7da8f42017-08-23 14:29:40 -070024
25#include <base/files/file_util.h>
Amin Hassani77c25fc2019-01-29 10:24:19 -080026#include <base/files/scoped_temp_dir.h>
Amin Hassanid7da8f42017-08-23 14:29:40 -070027#include <base/logging.h>
28#include <base/strings/string_number_conversions.h>
29#include <base/strings/string_split.h>
30#include <brillo/streams/file_stream.h>
31
32#include "update_engine/common/subprocess.h"
33#include "update_engine/common/utils.h"
Amin Hassani3cd4df12017-08-25 11:21:53 -070034#include "update_engine/payload_generator/deflate_utils.h"
Amin Hassanid7da8f42017-08-23 14:29:40 -070035#include "update_engine/payload_generator/delta_diff_generator.h"
36#include "update_engine/payload_generator/extent_ranges.h"
37#include "update_engine/payload_generator/extent_utils.h"
38#include "update_engine/update_metadata.pb.h"
39
Amin Hassani77c25fc2019-01-29 10:24:19 -080040using base::FilePath;
41using base::ScopedTempDir;
Amin Hassanid7da8f42017-08-23 14:29:40 -070042using std::string;
43using std::unique_ptr;
44using std::vector;
45
46namespace chromeos_update_engine {
47
48namespace {
49
Amin Hassanid7da8f42017-08-23 14:29:40 -070050// The size of the squashfs super block.
51constexpr size_t kSquashfsSuperBlockSize = 96;
52constexpr uint64_t kSquashfsCompressedBit = 1 << 24;
Amin Hassani3cd4df12017-08-25 11:21:53 -070053constexpr uint32_t kSquashfsZlibCompression = 1;
Amin Hassanid7da8f42017-08-23 14:29:40 -070054
Amin Hassani77c25fc2019-01-29 10:24:19 -080055constexpr char kUpdateEngineConf[] = "etc/update_engine.conf";
56
Amin Hassanid7da8f42017-08-23 14:29:40 -070057bool ReadSquashfsHeader(const brillo::Blob blob,
58 SquashfsFilesystem::SquashfsHeader* header) {
59 if (blob.size() < kSquashfsSuperBlockSize) {
60 return false;
61 }
62
63 memcpy(&header->magic, blob.data(), 4);
64 memcpy(&header->block_size, blob.data() + 12, 4);
65 memcpy(&header->compression_type, blob.data() + 20, 2);
66 memcpy(&header->major_version, blob.data() + 28, 2);
67 return true;
68}
69
70bool CheckHeader(const SquashfsFilesystem::SquashfsHeader& header) {
71 return header.magic == 0x73717368 && header.major_version == 4;
72}
73
74bool GetFileMapContent(const string& sqfs_path, string* map) {
75 // Create a tmp file
76 string map_file;
77 TEST_AND_RETURN_FALSE(
78 utils::MakeTempFile("squashfs_file_map.XXXXXX", &map_file, nullptr));
79 ScopedPathUnlinker map_unlinker(map_file);
80
81 // Run unsquashfs to get the system file map.
82 // unsquashfs -m <map-file> <squashfs-file>
83 vector<string> cmd = {"unsquashfs", "-m", map_file, sqfs_path};
Amin Hassani3a4caa12019-11-06 11:12:28 -080084 string stdout, stderr;
Amin Hassanid7da8f42017-08-23 14:29:40 -070085 int exit_code;
Amin Hassani3a4caa12019-11-06 11:12:28 -080086 if (!Subprocess::SynchronousExec(cmd, &exit_code, &stdout, &stderr) ||
Amin Hassanid7da8f42017-08-23 14:29:40 -070087 exit_code != 0) {
Amin Hassani3a4caa12019-11-06 11:12:28 -080088 LOG(ERROR) << "Failed to run `unsquashfs -m` with stdout content: "
89 << stdout << " and stderr content: " << stderr;
Amin Hassanid7da8f42017-08-23 14:29:40 -070090 return false;
91 }
92 TEST_AND_RETURN_FALSE(utils::ReadFile(map_file, map));
93 return true;
94}
95
Amin Hassani77c25fc2019-01-29 10:24:19 -080096bool GetUpdateEngineConfig(const std::string& sqfs_path, string* config) {
97 ScopedTempDir unsquash_dir;
98 if (!unsquash_dir.CreateUniqueTempDir()) {
99 PLOG(ERROR) << "Failed to create a temporary directory.";
100 return false;
101 }
102
103 // Run unsquashfs to extract update_engine.conf
104 // -f: To force overriding if the target directory exists.
105 // -d: The directory to unsquash the files.
106 vector<string> cmd = {"unsquashfs",
107 "-f",
108 "-d",
109 unsquash_dir.GetPath().value(),
110 sqfs_path,
111 kUpdateEngineConf};
Amin Hassani3a4caa12019-11-06 11:12:28 -0800112 string stdout, stderr;
Amin Hassani77c25fc2019-01-29 10:24:19 -0800113 int exit_code;
Amin Hassani3a4caa12019-11-06 11:12:28 -0800114 if (!Subprocess::SynchronousExec(cmd, &exit_code, &stdout, &stderr) ||
Amin Hassani77c25fc2019-01-29 10:24:19 -0800115 exit_code != 0) {
Amin Hassani3a4caa12019-11-06 11:12:28 -0800116 PLOG(ERROR) << "Failed to unsquashfs etc/update_engine.conf with stdout: "
117 << stdout << " and stderr: " << stderr;
Amin Hassani77c25fc2019-01-29 10:24:19 -0800118 return false;
119 }
120
121 auto config_path = unsquash_dir.GetPath().Append(kUpdateEngineConf);
122 string config_content;
123 if (!utils::ReadFile(config_path.value(), &config_content)) {
124 PLOG(ERROR) << "Failed to read " << config_path.value();
125 return false;
126 }
127
128 if (config_content.empty()) {
129 LOG(ERROR) << "update_engine config file was empty!!";
130 return false;
131 }
132
133 *config = std::move(config_content);
134 return true;
135}
136
Amin Hassanid7da8f42017-08-23 14:29:40 -0700137} // namespace
138
139bool SquashfsFilesystem::Init(const string& map,
Amin Hassani3cd4df12017-08-25 11:21:53 -0700140 const string& sqfs_path,
Amin Hassanid7da8f42017-08-23 14:29:40 -0700141 size_t size,
Amin Hassani3cd4df12017-08-25 11:21:53 -0700142 const SquashfsHeader& header,
143 bool extract_deflates) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700144 size_ = size;
Amin Hassani3cd4df12017-08-25 11:21:53 -0700145
146 bool is_zlib = header.compression_type == kSquashfsZlibCompression;
147 if (!is_zlib) {
148 LOG(WARNING) << "Filesystem is not Gzipped. Not filling deflates!";
149 }
150 vector<puffin::ByteExtent> zlib_blks;
151
Amin Hassanid7da8f42017-08-23 14:29:40 -0700152 // Reading files map. For the format of the file map look at the comments for
153 // |CreateFromFileMap()|.
154 auto lines = base::SplitStringPiece(map,
155 "\n",
156 base::WhitespaceHandling::KEEP_WHITESPACE,
157 base::SplitResult::SPLIT_WANT_NONEMPTY);
158 for (const auto& line : lines) {
159 auto splits =
160 base::SplitStringPiece(line,
161 " \t",
162 base::WhitespaceHandling::TRIM_WHITESPACE,
163 base::SplitResult::SPLIT_WANT_NONEMPTY);
164 // Only filename is invalid.
165 TEST_AND_RETURN_FALSE(splits.size() > 1);
166 uint64_t start;
167 TEST_AND_RETURN_FALSE(base::StringToUint64(splits[1], &start));
168 uint64_t cur_offset = start;
169 for (size_t i = 2; i < splits.size(); ++i) {
170 uint64_t blk_size;
171 TEST_AND_RETURN_FALSE(base::StringToUint64(splits[i], &blk_size));
172 // TODO(ahassani): For puffin push it into a proper list if uncompressed.
173 auto new_blk_size = blk_size & ~kSquashfsCompressedBit;
174 TEST_AND_RETURN_FALSE(new_blk_size <= header.block_size);
Amin Hassani3cd4df12017-08-25 11:21:53 -0700175 if (new_blk_size > 0 && !(blk_size & kSquashfsCompressedBit)) {
176 // Compressed block
177 if (is_zlib && extract_deflates) {
178 zlib_blks.emplace_back(cur_offset, new_blk_size);
179 }
180 }
Amin Hassanid7da8f42017-08-23 14:29:40 -0700181 cur_offset += new_blk_size;
182 }
183
184 // If size is zero do not add the file.
185 if (cur_offset - start > 0) {
186 File file;
187 file.name = splits[0].as_string();
188 file.extents = {ExtentForBytes(kBlockSize, start, cur_offset - start)};
189 files_.emplace_back(file);
190 }
191 }
192
193 // Sort all files by their offset in the squashfs.
194 std::sort(files_.begin(), files_.end(), [](const File& a, const File& b) {
195 return a.extents[0].start_block() < b.extents[0].start_block();
196 });
197 // If there is any overlap between two consecutive extents, remove them. Here
198 // we are assuming all files have exactly one extent. If this assumption
199 // changes then this implementation needs to change too.
200 for (auto first = files_.begin(), second = first + 1;
201 first != files_.end() && second != files_.end();
202 second = first + 1) {
203 auto first_begin = first->extents[0].start_block();
204 auto first_end = first_begin + first->extents[0].num_blocks();
205 auto second_begin = second->extents[0].start_block();
206 auto second_end = second_begin + second->extents[0].num_blocks();
207 // Remove the first file if the size is zero.
208 if (first_end == first_begin) {
209 first = files_.erase(first);
210 } else if (first_end > second_begin) { // We found a collision.
211 if (second_end <= first_end) {
212 // Second file is inside the first file, remove the second file.
213 second = files_.erase(second);
214 } else if (first_begin == second_begin) {
215 // First file is inside the second file, remove the first file.
216 first = files_.erase(first);
217 } else {
218 // Remove overlapping extents from the first file.
219 first->extents[0].set_num_blocks(second_begin - first_begin);
220 ++first;
221 }
222 } else {
223 ++first;
224 }
225 }
226
227 // Find all the metadata including superblock and add them to the list of
228 // files.
229 ExtentRanges file_extents;
230 for (const auto& file : files_) {
231 file_extents.AddExtents(file.extents);
232 }
Sen Jiang0a582fb2018-06-26 19:27:21 -0700233 vector<Extent> full = {ExtentForBytes(kBlockSize, 0, size_)};
Amin Hassanid7da8f42017-08-23 14:29:40 -0700234 auto metadata_extents = FilterExtentRanges(full, file_extents);
235 // For now there should be at most two extents. One for superblock and one for
236 // metadata at the end. Just create appropriate files with <metadata-i> name.
237 // We can add all these extents as one metadata too, but that violates the
238 // contiguous write optimization.
239 for (size_t i = 0; i < metadata_extents.size(); i++) {
240 File file;
241 file.name = "<metadata-" + std::to_string(i) + ">";
242 file.extents = {metadata_extents[i]};
243 files_.emplace_back(file);
244 }
245
246 // Do one last sort before returning.
247 std::sort(files_.begin(), files_.end(), [](const File& a, const File& b) {
248 return a.extents[0].start_block() < b.extents[0].start_block();
249 });
Amin Hassani3cd4df12017-08-25 11:21:53 -0700250
251 if (is_zlib && extract_deflates) {
252 // If it is infact gzipped, then the sqfs_path should be valid to read its
253 // content.
254 TEST_AND_RETURN_FALSE(!sqfs_path.empty());
255 if (zlib_blks.empty()) {
256 return true;
257 }
258
259 // Sort zlib blocks.
260 std::sort(zlib_blks.begin(),
261 zlib_blks.end(),
262 [](const puffin::ByteExtent& a, const puffin::ByteExtent& b) {
263 return a.offset < b.offset;
264 });
265
Amin Hassani5d185052019-04-23 07:28:30 -0700266 // Sometimes a squashfs can have a two files that are hard linked. In this
267 // case both files will have the same starting offset in the image and hence
268 // the same zlib blocks. So we need to remove these duplicates to eliminate
269 // further potential probems. As a matter of fact the next statement will
270 // fail if there are duplicates (there will be overlap between two blocks).
271 auto last = std::unique(zlib_blks.begin(), zlib_blks.end());
272 zlib_blks.erase(last, zlib_blks.end());
273
Amin Hassani3cd4df12017-08-25 11:21:53 -0700274 // Sanity check. Make sure zlib blocks are not overlapping.
275 auto result = std::adjacent_find(
276 zlib_blks.begin(),
277 zlib_blks.end(),
278 [](const puffin::ByteExtent& a, const puffin::ByteExtent& b) {
279 return (a.offset + a.length) > b.offset;
280 });
281 TEST_AND_RETURN_FALSE(result == zlib_blks.end());
282
283 vector<puffin::BitExtent> deflates;
284 TEST_AND_RETURN_FALSE(
285 puffin::LocateDeflatesInZlibBlocks(sqfs_path, zlib_blks, &deflates));
286
287 // Add deflates for each file.
288 for (auto& file : files_) {
289 file.deflates = deflate_utils::FindDeflates(file.extents, deflates);
290 }
291 }
Amin Hassanid7da8f42017-08-23 14:29:40 -0700292 return true;
293}
294
295unique_ptr<SquashfsFilesystem> SquashfsFilesystem::CreateFromFile(
Amin Hassani77c25fc2019-01-29 10:24:19 -0800296 const string& sqfs_path, bool extract_deflates, bool load_settings) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700297 if (sqfs_path.empty())
298 return nullptr;
299
300 brillo::StreamPtr sqfs_file =
Amin Hassani77c25fc2019-01-29 10:24:19 -0800301 brillo::FileStream::Open(FilePath(sqfs_path),
Amin Hassanid7da8f42017-08-23 14:29:40 -0700302 brillo::Stream::AccessMode::READ,
303 brillo::FileStream::Disposition::OPEN_EXISTING,
304 nullptr);
305 if (!sqfs_file) {
306 LOG(ERROR) << "Unable to open " << sqfs_path << " for reading.";
307 return nullptr;
308 }
309
310 SquashfsHeader header;
311 brillo::Blob blob(kSquashfsSuperBlockSize);
312 if (!sqfs_file->ReadAllBlocking(blob.data(), blob.size(), nullptr)) {
313 LOG(ERROR) << "Unable to read from file: " << sqfs_path;
314 return nullptr;
315 }
316 if (!ReadSquashfsHeader(blob, &header) || !CheckHeader(header)) {
317 // This is not necessary an error.
318 return nullptr;
319 }
320
321 // Read the map file.
322 string filemap;
323 if (!GetFileMapContent(sqfs_path, &filemap)) {
324 LOG(ERROR) << "Failed to produce squashfs map file: " << sqfs_path;
325 return nullptr;
326 }
327
328 unique_ptr<SquashfsFilesystem> sqfs(new SquashfsFilesystem());
Amin Hassani3cd4df12017-08-25 11:21:53 -0700329 if (!sqfs->Init(
330 filemap, sqfs_path, sqfs_file->GetSize(), header, extract_deflates)) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700331 LOG(ERROR) << "Failed to initialized the Squashfs file system";
332 return nullptr;
333 }
Amin Hassani3cd4df12017-08-25 11:21:53 -0700334
Amin Hassani77c25fc2019-01-29 10:24:19 -0800335 if (load_settings) {
336 if (!GetUpdateEngineConfig(sqfs_path, &sqfs->update_engine_config_)) {
337 return nullptr;
338 }
339 }
340
Amin Hassanid7da8f42017-08-23 14:29:40 -0700341 return sqfs;
342}
343
344unique_ptr<SquashfsFilesystem> SquashfsFilesystem::CreateFromFileMap(
345 const string& filemap, size_t size, const SquashfsHeader& header) {
346 if (!CheckHeader(header)) {
347 LOG(ERROR) << "Invalid Squashfs super block!";
348 return nullptr;
349 }
350
351 unique_ptr<SquashfsFilesystem> sqfs(new SquashfsFilesystem());
Amin Hassani3cd4df12017-08-25 11:21:53 -0700352 if (!sqfs->Init(filemap, "", size, header, false)) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700353 LOG(ERROR) << "Failed to initialize the Squashfs file system using filemap";
354 return nullptr;
355 }
356 // TODO(ahassani): Add a function that initializes the puffin related extents.
357 return sqfs;
358}
359
360size_t SquashfsFilesystem::GetBlockSize() const {
361 return kBlockSize;
362}
363
364size_t SquashfsFilesystem::GetBlockCount() const {
365 return size_ / kBlockSize;
366}
367
368bool SquashfsFilesystem::GetFiles(vector<File>* files) const {
369 files->insert(files->end(), files_.begin(), files_.end());
370 return true;
371}
372
373bool SquashfsFilesystem::LoadSettings(brillo::KeyValueStore* store) const {
Amin Hassani77c25fc2019-01-29 10:24:19 -0800374 if (!store->LoadFromString(update_engine_config_)) {
375 LOG(ERROR) << "Failed to load the settings with config: "
376 << update_engine_config_;
377 return false;
378 }
379 return true;
Amin Hassanid7da8f42017-08-23 14:29:40 -0700380}
381
382bool SquashfsFilesystem::IsSquashfsImage(const brillo::Blob& blob) {
383 SquashfsHeader header;
384 return ReadSquashfsHeader(blob, &header) && CheckHeader(header);
385}
Amin Hassanid7da8f42017-08-23 14:29:40 -0700386} // namespace chromeos_update_engine