squashfs_filesystem.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. //
  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. #include "update_engine/payload_generator/squashfs_filesystem.h"
  17. #include <fcntl.h>
  18. #include <algorithm>
  19. #include <string>
  20. #include <utility>
  21. #include <base/files/file_util.h>
  22. #include <base/logging.h>
  23. #include <base/strings/string_number_conversions.h>
  24. #include <base/strings/string_split.h>
  25. #include <brillo/streams/file_stream.h>
  26. #include "update_engine/common/subprocess.h"
  27. #include "update_engine/common/utils.h"
  28. #include "update_engine/payload_generator/deflate_utils.h"
  29. #include "update_engine/payload_generator/delta_diff_generator.h"
  30. #include "update_engine/payload_generator/extent_ranges.h"
  31. #include "update_engine/payload_generator/extent_utils.h"
  32. #include "update_engine/update_metadata.pb.h"
  33. using std::string;
  34. using std::unique_ptr;
  35. using std::vector;
  36. namespace chromeos_update_engine {
  37. namespace {
  38. // The size of the squashfs super block.
  39. constexpr size_t kSquashfsSuperBlockSize = 96;
  40. constexpr uint64_t kSquashfsCompressedBit = 1 << 24;
  41. constexpr uint32_t kSquashfsZlibCompression = 1;
  42. bool ReadSquashfsHeader(const brillo::Blob blob,
  43. SquashfsFilesystem::SquashfsHeader* header) {
  44. if (blob.size() < kSquashfsSuperBlockSize) {
  45. return false;
  46. }
  47. memcpy(&header->magic, blob.data(), 4);
  48. memcpy(&header->block_size, blob.data() + 12, 4);
  49. memcpy(&header->compression_type, blob.data() + 20, 2);
  50. memcpy(&header->major_version, blob.data() + 28, 2);
  51. return true;
  52. }
  53. bool CheckHeader(const SquashfsFilesystem::SquashfsHeader& header) {
  54. return header.magic == 0x73717368 && header.major_version == 4;
  55. }
  56. bool GetFileMapContent(const string& sqfs_path, string* map) {
  57. // Create a tmp file
  58. string map_file;
  59. TEST_AND_RETURN_FALSE(
  60. utils::MakeTempFile("squashfs_file_map.XXXXXX", &map_file, nullptr));
  61. ScopedPathUnlinker map_unlinker(map_file);
  62. // Run unsquashfs to get the system file map.
  63. // unsquashfs -m <map-file> <squashfs-file>
  64. vector<string> cmd = {"unsquashfs", "-m", map_file, sqfs_path};
  65. string stdout;
  66. int exit_code;
  67. if (!Subprocess::SynchronousExec(cmd, &exit_code, &stdout) ||
  68. exit_code != 0) {
  69. LOG(ERROR) << "Failed to run unsquashfs -m. The stdout content was: "
  70. << stdout;
  71. return false;
  72. }
  73. TEST_AND_RETURN_FALSE(utils::ReadFile(map_file, map));
  74. return true;
  75. }
  76. } // namespace
  77. bool SquashfsFilesystem::Init(const string& map,
  78. const string& sqfs_path,
  79. size_t size,
  80. const SquashfsHeader& header,
  81. bool extract_deflates) {
  82. size_ = size;
  83. bool is_zlib = header.compression_type == kSquashfsZlibCompression;
  84. if (!is_zlib) {
  85. LOG(WARNING) << "Filesystem is not Gzipped. Not filling deflates!";
  86. }
  87. vector<puffin::ByteExtent> zlib_blks;
  88. // Reading files map. For the format of the file map look at the comments for
  89. // |CreateFromFileMap()|.
  90. auto lines = base::SplitStringPiece(map,
  91. "\n",
  92. base::WhitespaceHandling::KEEP_WHITESPACE,
  93. base::SplitResult::SPLIT_WANT_NONEMPTY);
  94. for (const auto& line : lines) {
  95. auto splits =
  96. base::SplitStringPiece(line,
  97. " \t",
  98. base::WhitespaceHandling::TRIM_WHITESPACE,
  99. base::SplitResult::SPLIT_WANT_NONEMPTY);
  100. // Only filename is invalid.
  101. TEST_AND_RETURN_FALSE(splits.size() > 1);
  102. uint64_t start;
  103. TEST_AND_RETURN_FALSE(base::StringToUint64(splits[1], &start));
  104. uint64_t cur_offset = start;
  105. for (size_t i = 2; i < splits.size(); ++i) {
  106. uint64_t blk_size;
  107. TEST_AND_RETURN_FALSE(base::StringToUint64(splits[i], &blk_size));
  108. // TODO(ahassani): For puffin push it into a proper list if uncompressed.
  109. auto new_blk_size = blk_size & ~kSquashfsCompressedBit;
  110. TEST_AND_RETURN_FALSE(new_blk_size <= header.block_size);
  111. if (new_blk_size > 0 && !(blk_size & kSquashfsCompressedBit)) {
  112. // Compressed block
  113. if (is_zlib && extract_deflates) {
  114. zlib_blks.emplace_back(cur_offset, new_blk_size);
  115. }
  116. }
  117. cur_offset += new_blk_size;
  118. }
  119. // If size is zero do not add the file.
  120. if (cur_offset - start > 0) {
  121. File file;
  122. file.name = splits[0].as_string();
  123. file.extents = {ExtentForBytes(kBlockSize, start, cur_offset - start)};
  124. files_.emplace_back(file);
  125. }
  126. }
  127. // Sort all files by their offset in the squashfs.
  128. std::sort(files_.begin(), files_.end(), [](const File& a, const File& b) {
  129. return a.extents[0].start_block() < b.extents[0].start_block();
  130. });
  131. // If there is any overlap between two consecutive extents, remove them. Here
  132. // we are assuming all files have exactly one extent. If this assumption
  133. // changes then this implementation needs to change too.
  134. for (auto first = files_.begin(), second = first + 1;
  135. first != files_.end() && second != files_.end();
  136. second = first + 1) {
  137. auto first_begin = first->extents[0].start_block();
  138. auto first_end = first_begin + first->extents[0].num_blocks();
  139. auto second_begin = second->extents[0].start_block();
  140. auto second_end = second_begin + second->extents[0].num_blocks();
  141. // Remove the first file if the size is zero.
  142. if (first_end == first_begin) {
  143. first = files_.erase(first);
  144. } else if (first_end > second_begin) { // We found a collision.
  145. if (second_end <= first_end) {
  146. // Second file is inside the first file, remove the second file.
  147. second = files_.erase(second);
  148. } else if (first_begin == second_begin) {
  149. // First file is inside the second file, remove the first file.
  150. first = files_.erase(first);
  151. } else {
  152. // Remove overlapping extents from the first file.
  153. first->extents[0].set_num_blocks(second_begin - first_begin);
  154. ++first;
  155. }
  156. } else {
  157. ++first;
  158. }
  159. }
  160. // Find all the metadata including superblock and add them to the list of
  161. // files.
  162. ExtentRanges file_extents;
  163. for (const auto& file : files_) {
  164. file_extents.AddExtents(file.extents);
  165. }
  166. vector<Extent> full = {ExtentForBytes(kBlockSize, 0, size_)};
  167. auto metadata_extents = FilterExtentRanges(full, file_extents);
  168. // For now there should be at most two extents. One for superblock and one for
  169. // metadata at the end. Just create appropriate files with <metadata-i> name.
  170. // We can add all these extents as one metadata too, but that violates the
  171. // contiguous write optimization.
  172. for (size_t i = 0; i < metadata_extents.size(); i++) {
  173. File file;
  174. file.name = "<metadata-" + std::to_string(i) + ">";
  175. file.extents = {metadata_extents[i]};
  176. files_.emplace_back(file);
  177. }
  178. // Do one last sort before returning.
  179. std::sort(files_.begin(), files_.end(), [](const File& a, const File& b) {
  180. return a.extents[0].start_block() < b.extents[0].start_block();
  181. });
  182. if (is_zlib && extract_deflates) {
  183. // If it is infact gzipped, then the sqfs_path should be valid to read its
  184. // content.
  185. TEST_AND_RETURN_FALSE(!sqfs_path.empty());
  186. if (zlib_blks.empty()) {
  187. return true;
  188. }
  189. // Sort zlib blocks.
  190. std::sort(zlib_blks.begin(),
  191. zlib_blks.end(),
  192. [](const puffin::ByteExtent& a, const puffin::ByteExtent& b) {
  193. return a.offset < b.offset;
  194. });
  195. // Sanity check. Make sure zlib blocks are not overlapping.
  196. auto result = std::adjacent_find(
  197. zlib_blks.begin(),
  198. zlib_blks.end(),
  199. [](const puffin::ByteExtent& a, const puffin::ByteExtent& b) {
  200. return (a.offset + a.length) > b.offset;
  201. });
  202. TEST_AND_RETURN_FALSE(result == zlib_blks.end());
  203. vector<puffin::BitExtent> deflates;
  204. TEST_AND_RETURN_FALSE(
  205. puffin::LocateDeflatesInZlibBlocks(sqfs_path, zlib_blks, &deflates));
  206. // Add deflates for each file.
  207. for (auto& file : files_) {
  208. file.deflates = deflate_utils::FindDeflates(file.extents, deflates);
  209. }
  210. }
  211. return true;
  212. }
  213. unique_ptr<SquashfsFilesystem> SquashfsFilesystem::CreateFromFile(
  214. const string& sqfs_path, bool extract_deflates) {
  215. if (sqfs_path.empty())
  216. return nullptr;
  217. brillo::StreamPtr sqfs_file =
  218. brillo::FileStream::Open(base::FilePath(sqfs_path),
  219. brillo::Stream::AccessMode::READ,
  220. brillo::FileStream::Disposition::OPEN_EXISTING,
  221. nullptr);
  222. if (!sqfs_file) {
  223. LOG(ERROR) << "Unable to open " << sqfs_path << " for reading.";
  224. return nullptr;
  225. }
  226. SquashfsHeader header;
  227. brillo::Blob blob(kSquashfsSuperBlockSize);
  228. if (!sqfs_file->ReadAllBlocking(blob.data(), blob.size(), nullptr)) {
  229. LOG(ERROR) << "Unable to read from file: " << sqfs_path;
  230. return nullptr;
  231. }
  232. if (!ReadSquashfsHeader(blob, &header) || !CheckHeader(header)) {
  233. // This is not necessary an error.
  234. return nullptr;
  235. }
  236. // Read the map file.
  237. string filemap;
  238. if (!GetFileMapContent(sqfs_path, &filemap)) {
  239. LOG(ERROR) << "Failed to produce squashfs map file: " << sqfs_path;
  240. return nullptr;
  241. }
  242. unique_ptr<SquashfsFilesystem> sqfs(new SquashfsFilesystem());
  243. if (!sqfs->Init(
  244. filemap, sqfs_path, sqfs_file->GetSize(), header, extract_deflates)) {
  245. LOG(ERROR) << "Failed to initialized the Squashfs file system";
  246. return nullptr;
  247. }
  248. return sqfs;
  249. }
  250. unique_ptr<SquashfsFilesystem> SquashfsFilesystem::CreateFromFileMap(
  251. const string& filemap, size_t size, const SquashfsHeader& header) {
  252. if (!CheckHeader(header)) {
  253. LOG(ERROR) << "Invalid Squashfs super block!";
  254. return nullptr;
  255. }
  256. unique_ptr<SquashfsFilesystem> sqfs(new SquashfsFilesystem());
  257. if (!sqfs->Init(filemap, "", size, header, false)) {
  258. LOG(ERROR) << "Failed to initialize the Squashfs file system using filemap";
  259. return nullptr;
  260. }
  261. // TODO(ahassani): Add a function that initializes the puffin related extents.
  262. return sqfs;
  263. }
  264. size_t SquashfsFilesystem::GetBlockSize() const {
  265. return kBlockSize;
  266. }
  267. size_t SquashfsFilesystem::GetBlockCount() const {
  268. return size_ / kBlockSize;
  269. }
  270. bool SquashfsFilesystem::GetFiles(vector<File>* files) const {
  271. files->insert(files->end(), files_.begin(), files_.end());
  272. return true;
  273. }
  274. bool SquashfsFilesystem::LoadSettings(brillo::KeyValueStore* store) const {
  275. // Settings not supported in squashfs.
  276. LOG(ERROR) << "squashfs doesn't support LoadSettings().";
  277. return false;
  278. }
  279. bool SquashfsFilesystem::IsSquashfsImage(const brillo::Blob& blob) {
  280. SquashfsHeader header;
  281. return ReadSquashfsHeader(blob, &header) && CheckHeader(header);
  282. }
  283. } // namespace chromeos_update_engine