ext4_parser/
lib.rs

1// Copyright 2019 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::directory::ExtDirectory;
6use crate::file::ExtFile;
7use crate::types::ExtAttributes;
8use ext4_read_only::parser::Parser;
9use ext4_read_only::readers::{BlockDeviceReader, Reader, VmoReader};
10use ext4_read_only::structs::{self, EntryType, MIN_EXT4_SIZE};
11use fidl::endpoints::ClientEnd;
12use fidl_fuchsia_hardware_block::BlockMarker;
13use log::error;
14use std::sync::Arc;
15
16mod directory;
17mod file;
18mod node;
19mod types;
20
21pub enum FsSourceType {
22    BlockDevice(ClientEnd<BlockMarker>),
23    Vmo(zx::Vmo),
24}
25
26#[derive(Debug, PartialEq)]
27pub enum ConstructFsError {
28    VmoReadError(zx::Status),
29    ParsingError(structs::ParsingError),
30    FileVmoError(zx::Status),
31    NodeError(zx::Status),
32}
33
34impl From<structs::ParsingError> for ConstructFsError {
35    fn from(value: structs::ParsingError) -> Self {
36        Self::ParsingError(value)
37    }
38}
39
40pub fn construct_fs(source: FsSourceType) -> Result<Arc<ExtDirectory>, ConstructFsError> {
41    let reader: Box<dyn Reader> = match source {
42        FsSourceType::BlockDevice(block_device) => {
43            Box::new(BlockDeviceReader::from_client_end(block_device).map_err(|e| {
44                error!("Error constructing file system: {}", e);
45                ConstructFsError::VmoReadError(zx::Status::IO_INVALID)
46            })?)
47        }
48        FsSourceType::Vmo(vmo) => {
49            let size = vmo.get_size().map_err(ConstructFsError::VmoReadError)?;
50            if size < MIN_EXT4_SIZE as u64 {
51                // Too small to even fit the first copy of the ext4 Super Block.
52                return Err(ConstructFsError::VmoReadError(zx::Status::NO_SPACE));
53            }
54
55            Box::new(VmoReader::new(Arc::new(vmo)))
56        }
57    };
58
59    let parser = Parser::new(reader);
60    build_fs_dir(&parser, structs::ROOT_INODE_NUM)
61}
62
63fn build_fs_dir(parser: &Parser, ino: u32) -> Result<Arc<ExtDirectory>, ConstructFsError> {
64    let inode = parser.inode(ino)?;
65    let entries = parser.entries_from_inode(&inode)?;
66    let dir = ExtDirectory::new(ino as u64, ExtAttributes::from_inode(inode));
67
68    for entry in entries {
69        let entry_name = entry.name()?;
70        if entry_name == "." || entry_name == ".." {
71            continue;
72        }
73
74        let entry_ino = u32::from(entry.e2d_ino);
75        match EntryType::from_u8(entry.e2d_type)? {
76            EntryType::Directory => {
77                dir.insert_child(entry_name, build_fs_dir(parser, entry_ino)?)
78                    .map_err(ConstructFsError::NodeError)?;
79            }
80            EntryType::RegularFile => {
81                dir.insert_child(entry_name, build_fs_file(parser, entry_ino)?)
82                    .map_err(ConstructFsError::NodeError)?;
83            }
84            _ => {
85                // TODO(https://fxbug.dev/42073143): Handle other types.
86            }
87        }
88    }
89
90    Ok(dir)
91}
92
93fn build_fs_file(parser: &Parser, ino: u32) -> Result<Arc<ExtFile>, ConstructFsError> {
94    let inode = parser.inode(ino)?;
95    let data = parser.read_data(ino)?;
96    let file = ExtFile::from_data(ino as u64, ExtAttributes::from_inode(inode), data)
97        .map_err(ConstructFsError::NodeError)?;
98    Ok(file)
99}
100
101#[cfg(test)]
102mod tests {
103    use super::{FsSourceType, construct_fs};
104
105    use ext4_read_only::structs::MIN_EXT4_SIZE;
106    use fidl_fuchsia_io as fio;
107    use fuchsia_fs::directory::{DirEntry, DirentKind, open_file, open_node, readdir};
108    use fuchsia_fs::file::read_to_string;
109    use std::fs;
110    use zx::{Status, Vmo};
111
112    #[fuchsia::test]
113    fn image_too_small() {
114        let vmo = Vmo::create(10).expect("VMO is created");
115        vmo.write(b"too small", 0).expect("VMO write() succeeds");
116        let buffer = FsSourceType::Vmo(vmo);
117
118        assert!(construct_fs(buffer).is_err(), "Expected failed parsing of VMO.");
119    }
120
121    #[fuchsia::test]
122    fn invalid_fs() {
123        let vmo = Vmo::create(MIN_EXT4_SIZE as u64).expect("VMO is created");
124        vmo.write(b"not ext4", 0).expect("VMO write() succeeds");
125        let buffer = FsSourceType::Vmo(vmo);
126
127        assert!(construct_fs(buffer).is_err(), "Expected failed parsing of VMO.");
128    }
129
130    #[fuchsia::test]
131    async fn list_root() {
132        let data = fs::read("/pkg/data/nest.img").expect("Unable to read file");
133        let vmo = Vmo::create(data.len() as u64).expect("VMO is created");
134        vmo.write(data.as_slice(), 0).expect("VMO write() succeeds");
135        let buffer = FsSourceType::Vmo(vmo);
136
137        let tree = construct_fs(buffer).expect("construct_fs parses the vmo");
138        let root = vfs::directory::serve(tree, fio::PERM_READABLE);
139
140        let expected = vec![
141            DirEntry { name: String::from("file1"), kind: DirentKind::File },
142            DirEntry { name: String::from("inner"), kind: DirentKind::Directory },
143            DirEntry { name: String::from("lost+found"), kind: DirentKind::Directory },
144        ];
145        assert_eq!(readdir(&root).await.unwrap(), expected);
146
147        let file = open_file(&root, "file1", fio::PERM_READABLE).await.unwrap();
148        assert_eq!(read_to_string(&file).await.unwrap(), "file1 contents.\n");
149        file.close().await.unwrap().map_err(zx::Status::from_raw).unwrap();
150        root.close().await.unwrap().map_err(zx::Status::from_raw).unwrap();
151    }
152
153    #[fuchsia::test]
154    async fn get_dac_attributes() {
155        let data = fs::read("/pkg/data/dac_attributes.img").expect("Unable to read file");
156        let vmo = Vmo::create(data.len() as u64).expect("VMO is created");
157        vmo.write(data.as_slice(), 0).expect("VMO write() succeeds");
158        let buffer = FsSourceType::Vmo(vmo);
159
160        let tree = construct_fs(buffer).expect("construct_fs parses the VMO");
161        let root = vfs::directory::serve(tree, fio::PERM_READABLE);
162
163        let expected_entries = vec![
164            DirEntry { name: String::from("dir_1000"), kind: DirentKind::Directory },
165            DirEntry { name: String::from("dir_root"), kind: DirentKind::Directory },
166            DirEntry { name: String::from("file_1000"), kind: DirentKind::File },
167            DirEntry { name: String::from("file_root"), kind: DirentKind::File },
168            DirEntry { name: String::from("lost+found"), kind: DirentKind::Directory },
169        ];
170        assert_eq!(readdir(&root).await.unwrap(), expected_entries);
171
172        #[derive(Debug, PartialEq)]
173        struct Node {
174            name: String,
175            mode: u32,
176            uid: u32,
177            gid: u32,
178        }
179
180        let expected_attributes = vec![
181            Node { name: String::from("dir_1000"), mode: 0x416D, uid: 1000, gid: 1000 },
182            Node { name: String::from("dir_root"), mode: 0x4140, uid: 0, gid: 0 },
183            Node { name: String::from("file_1000"), mode: 0x8124, uid: 1000, gid: 1000 },
184            Node { name: String::from("file_root"), mode: 0x8100, uid: 0, gid: 0 },
185        ];
186
187        let attributes_query = fio::NodeAttributesQuery::MODE
188            | fio::NodeAttributesQuery::UID
189            | fio::NodeAttributesQuery::GID;
190        for expected_node in &expected_attributes {
191            let node_proxy = open_node(&root, expected_node.name.as_str(), fio::PERM_READABLE)
192                .await
193                .expect("node open failed");
194            let (mut_attrs, _immut_attrs) = node_proxy
195                .get_attributes(attributes_query)
196                .await
197                .expect("node get_attributes() failed")
198                .map_err(Status::from_raw)
199                .expect("node get_attributes() error");
200
201            let node = Node {
202                name: expected_node.name.clone(),
203                mode: mut_attrs.mode.expect("node attributes missing mode"),
204                uid: mut_attrs.uid.expect("node attributes missing uid"),
205                gid: mut_attrs.gid.expect("node attributes missing gid"),
206            };
207
208            node_proxy
209                .close()
210                .await
211                .expect("node close failed")
212                .map_err(Status::from_raw)
213                .expect("node close error");
214
215            assert_eq!(node, *expected_node);
216        }
217
218        root.close().await.unwrap().map_err(Status::from_raw).unwrap();
219    }
220}