blob: c423b69c797612432e664d8c41ce6cee3952737b [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};
84 string stdout;
85 int exit_code;
86 if (!Subprocess::SynchronousExec(cmd, &exit_code, &stdout) ||
87 exit_code != 0) {
88 LOG(ERROR) << "Failed to run unsquashfs -m. The stdout content was: "
89 << stdout;
90 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};
112 int exit_code;
113 if (!Subprocess::SynchronousExec(cmd, &exit_code, nullptr) ||
114 exit_code != 0) {
115 PLOG(ERROR) << "Failed to unsquashfs etc/update_engine.conf: ";
116 return false;
117 }
118
119 auto config_path = unsquash_dir.GetPath().Append(kUpdateEngineConf);
120 string config_content;
121 if (!utils::ReadFile(config_path.value(), &config_content)) {
122 PLOG(ERROR) << "Failed to read " << config_path.value();
123 return false;
124 }
125
126 if (config_content.empty()) {
127 LOG(ERROR) << "update_engine config file was empty!!";
128 return false;
129 }
130
131 *config = std::move(config_content);
132 return true;
133}
134
Amin Hassanid7da8f42017-08-23 14:29:40 -0700135} // namespace
136
137bool SquashfsFilesystem::Init(const string& map,
Amin Hassani3cd4df12017-08-25 11:21:53 -0700138 const string& sqfs_path,
Amin Hassanid7da8f42017-08-23 14:29:40 -0700139 size_t size,
Amin Hassani3cd4df12017-08-25 11:21:53 -0700140 const SquashfsHeader& header,
141 bool extract_deflates) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700142 size_ = size;
Amin Hassani3cd4df12017-08-25 11:21:53 -0700143
144 bool is_zlib = header.compression_type == kSquashfsZlibCompression;
145 if (!is_zlib) {
146 LOG(WARNING) << "Filesystem is not Gzipped. Not filling deflates!";
147 }
148 vector<puffin::ByteExtent> zlib_blks;
149
Amin Hassanid7da8f42017-08-23 14:29:40 -0700150 // Reading files map. For the format of the file map look at the comments for
151 // |CreateFromFileMap()|.
152 auto lines = base::SplitStringPiece(map,
153 "\n",
154 base::WhitespaceHandling::KEEP_WHITESPACE,
155 base::SplitResult::SPLIT_WANT_NONEMPTY);
156 for (const auto& line : lines) {
157 auto splits =
158 base::SplitStringPiece(line,
159 " \t",
160 base::WhitespaceHandling::TRIM_WHITESPACE,
161 base::SplitResult::SPLIT_WANT_NONEMPTY);
162 // Only filename is invalid.
163 TEST_AND_RETURN_FALSE(splits.size() > 1);
164 uint64_t start;
165 TEST_AND_RETURN_FALSE(base::StringToUint64(splits[1], &start));
166 uint64_t cur_offset = start;
167 for (size_t i = 2; i < splits.size(); ++i) {
168 uint64_t blk_size;
169 TEST_AND_RETURN_FALSE(base::StringToUint64(splits[i], &blk_size));
170 // TODO(ahassani): For puffin push it into a proper list if uncompressed.
171 auto new_blk_size = blk_size & ~kSquashfsCompressedBit;
172 TEST_AND_RETURN_FALSE(new_blk_size <= header.block_size);
Amin Hassani3cd4df12017-08-25 11:21:53 -0700173 if (new_blk_size > 0 && !(blk_size & kSquashfsCompressedBit)) {
174 // Compressed block
175 if (is_zlib && extract_deflates) {
176 zlib_blks.emplace_back(cur_offset, new_blk_size);
177 }
178 }
Amin Hassanid7da8f42017-08-23 14:29:40 -0700179 cur_offset += new_blk_size;
180 }
181
182 // If size is zero do not add the file.
183 if (cur_offset - start > 0) {
184 File file;
185 file.name = splits[0].as_string();
186 file.extents = {ExtentForBytes(kBlockSize, start, cur_offset - start)};
187 files_.emplace_back(file);
188 }
189 }
190
191 // Sort all files by their offset in the squashfs.
192 std::sort(files_.begin(), files_.end(), [](const File& a, const File& b) {
193 return a.extents[0].start_block() < b.extents[0].start_block();
194 });
195 // If there is any overlap between two consecutive extents, remove them. Here
196 // we are assuming all files have exactly one extent. If this assumption
197 // changes then this implementation needs to change too.
198 for (auto first = files_.begin(), second = first + 1;
199 first != files_.end() && second != files_.end();
200 second = first + 1) {
201 auto first_begin = first->extents[0].start_block();
202 auto first_end = first_begin + first->extents[0].num_blocks();
203 auto second_begin = second->extents[0].start_block();
204 auto second_end = second_begin + second->extents[0].num_blocks();
205 // Remove the first file if the size is zero.
206 if (first_end == first_begin) {
207 first = files_.erase(first);
208 } else if (first_end > second_begin) { // We found a collision.
209 if (second_end <= first_end) {
210 // Second file is inside the first file, remove the second file.
211 second = files_.erase(second);
212 } else if (first_begin == second_begin) {
213 // First file is inside the second file, remove the first file.
214 first = files_.erase(first);
215 } else {
216 // Remove overlapping extents from the first file.
217 first->extents[0].set_num_blocks(second_begin - first_begin);
218 ++first;
219 }
220 } else {
221 ++first;
222 }
223 }
224
225 // Find all the metadata including superblock and add them to the list of
226 // files.
227 ExtentRanges file_extents;
228 for (const auto& file : files_) {
229 file_extents.AddExtents(file.extents);
230 }
Sen Jiang0a582fb2018-06-26 19:27:21 -0700231 vector<Extent> full = {ExtentForBytes(kBlockSize, 0, size_)};
Amin Hassanid7da8f42017-08-23 14:29:40 -0700232 auto metadata_extents = FilterExtentRanges(full, file_extents);
233 // For now there should be at most two extents. One for superblock and one for
234 // metadata at the end. Just create appropriate files with <metadata-i> name.
235 // We can add all these extents as one metadata too, but that violates the
236 // contiguous write optimization.
237 for (size_t i = 0; i < metadata_extents.size(); i++) {
238 File file;
239 file.name = "<metadata-" + std::to_string(i) + ">";
240 file.extents = {metadata_extents[i]};
241 files_.emplace_back(file);
242 }
243
244 // Do one last sort before returning.
245 std::sort(files_.begin(), files_.end(), [](const File& a, const File& b) {
246 return a.extents[0].start_block() < b.extents[0].start_block();
247 });
Amin Hassani3cd4df12017-08-25 11:21:53 -0700248
249 if (is_zlib && extract_deflates) {
250 // If it is infact gzipped, then the sqfs_path should be valid to read its
251 // content.
252 TEST_AND_RETURN_FALSE(!sqfs_path.empty());
253 if (zlib_blks.empty()) {
254 return true;
255 }
256
257 // Sort zlib blocks.
258 std::sort(zlib_blks.begin(),
259 zlib_blks.end(),
260 [](const puffin::ByteExtent& a, const puffin::ByteExtent& b) {
261 return a.offset < b.offset;
262 });
263
264 // Sanity check. Make sure zlib blocks are not overlapping.
265 auto result = std::adjacent_find(
266 zlib_blks.begin(),
267 zlib_blks.end(),
268 [](const puffin::ByteExtent& a, const puffin::ByteExtent& b) {
269 return (a.offset + a.length) > b.offset;
270 });
271 TEST_AND_RETURN_FALSE(result == zlib_blks.end());
272
273 vector<puffin::BitExtent> deflates;
274 TEST_AND_RETURN_FALSE(
275 puffin::LocateDeflatesInZlibBlocks(sqfs_path, zlib_blks, &deflates));
276
277 // Add deflates for each file.
278 for (auto& file : files_) {
279 file.deflates = deflate_utils::FindDeflates(file.extents, deflates);
280 }
281 }
Amin Hassanid7da8f42017-08-23 14:29:40 -0700282 return true;
283}
284
285unique_ptr<SquashfsFilesystem> SquashfsFilesystem::CreateFromFile(
Amin Hassani77c25fc2019-01-29 10:24:19 -0800286 const string& sqfs_path, bool extract_deflates, bool load_settings) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700287 if (sqfs_path.empty())
288 return nullptr;
289
290 brillo::StreamPtr sqfs_file =
Amin Hassani77c25fc2019-01-29 10:24:19 -0800291 brillo::FileStream::Open(FilePath(sqfs_path),
Amin Hassanid7da8f42017-08-23 14:29:40 -0700292 brillo::Stream::AccessMode::READ,
293 brillo::FileStream::Disposition::OPEN_EXISTING,
294 nullptr);
295 if (!sqfs_file) {
296 LOG(ERROR) << "Unable to open " << sqfs_path << " for reading.";
297 return nullptr;
298 }
299
300 SquashfsHeader header;
301 brillo::Blob blob(kSquashfsSuperBlockSize);
302 if (!sqfs_file->ReadAllBlocking(blob.data(), blob.size(), nullptr)) {
303 LOG(ERROR) << "Unable to read from file: " << sqfs_path;
304 return nullptr;
305 }
306 if (!ReadSquashfsHeader(blob, &header) || !CheckHeader(header)) {
307 // This is not necessary an error.
308 return nullptr;
309 }
310
311 // Read the map file.
312 string filemap;
313 if (!GetFileMapContent(sqfs_path, &filemap)) {
314 LOG(ERROR) << "Failed to produce squashfs map file: " << sqfs_path;
315 return nullptr;
316 }
317
318 unique_ptr<SquashfsFilesystem> sqfs(new SquashfsFilesystem());
Amin Hassani3cd4df12017-08-25 11:21:53 -0700319 if (!sqfs->Init(
320 filemap, sqfs_path, sqfs_file->GetSize(), header, extract_deflates)) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700321 LOG(ERROR) << "Failed to initialized the Squashfs file system";
322 return nullptr;
323 }
Amin Hassani3cd4df12017-08-25 11:21:53 -0700324
Amin Hassani77c25fc2019-01-29 10:24:19 -0800325 if (load_settings) {
326 if (!GetUpdateEngineConfig(sqfs_path, &sqfs->update_engine_config_)) {
327 return nullptr;
328 }
329 }
330
Amin Hassanid7da8f42017-08-23 14:29:40 -0700331 return sqfs;
332}
333
334unique_ptr<SquashfsFilesystem> SquashfsFilesystem::CreateFromFileMap(
335 const string& filemap, size_t size, const SquashfsHeader& header) {
336 if (!CheckHeader(header)) {
337 LOG(ERROR) << "Invalid Squashfs super block!";
338 return nullptr;
339 }
340
341 unique_ptr<SquashfsFilesystem> sqfs(new SquashfsFilesystem());
Amin Hassani3cd4df12017-08-25 11:21:53 -0700342 if (!sqfs->Init(filemap, "", size, header, false)) {
Amin Hassanid7da8f42017-08-23 14:29:40 -0700343 LOG(ERROR) << "Failed to initialize the Squashfs file system using filemap";
344 return nullptr;
345 }
346 // TODO(ahassani): Add a function that initializes the puffin related extents.
347 return sqfs;
348}
349
350size_t SquashfsFilesystem::GetBlockSize() const {
351 return kBlockSize;
352}
353
354size_t SquashfsFilesystem::GetBlockCount() const {
355 return size_ / kBlockSize;
356}
357
358bool SquashfsFilesystem::GetFiles(vector<File>* files) const {
359 files->insert(files->end(), files_.begin(), files_.end());
360 return true;
361}
362
363bool SquashfsFilesystem::LoadSettings(brillo::KeyValueStore* store) const {
Amin Hassani77c25fc2019-01-29 10:24:19 -0800364 if (!store->LoadFromString(update_engine_config_)) {
365 LOG(ERROR) << "Failed to load the settings with config: "
366 << update_engine_config_;
367 return false;
368 }
369 return true;
Amin Hassanid7da8f42017-08-23 14:29:40 -0700370}
371
372bool SquashfsFilesystem::IsSquashfsImage(const brillo::Blob& blob) {
373 SquashfsHeader header;
374 return ReadSquashfsHeader(blob, &header) && CheckHeader(header);
375}
Amin Hassanid7da8f42017-08-23 14:29:40 -0700376} // namespace chromeos_update_engine