• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 use anyhow::{anyhow, bail, Result};
17 use std::collections::HashMap;
18 use std::ffi::{CStr, CString};
19 use std::io;
20 use std::os::unix::ffi::OsStrExt;
21 
22 /// `InodeTable` is a table of `InodeData` indexed by `Inode`.
23 #[derive(Debug)]
24 pub struct InodeTable {
25     table: Vec<InodeData>,
26 }
27 
28 /// `Inode` is the handle (or index in the table) to `InodeData` which represents an inode.
29 pub type Inode = u64;
30 
31 const INVALID: Inode = 0;
32 const ROOT: Inode = 1;
33 
34 const DEFAULT_DIR_MODE: u32 = libc::S_IRUSR | libc::S_IXUSR;
35 // b/264668376 some files in APK don't have unix permissions specified. Default to 400
36 // otherwise those files won't be readable even by the owner.
37 const DEFAULT_FILE_MODE: u32 = libc::S_IRUSR;
38 
39 /// `InodeData` represents an inode which has metadata about a file or a directory
40 #[derive(Debug)]
41 pub struct InodeData {
42     /// Size of the file that this inode represents. In case when the file is a directory, this
43     // is zero.
44     pub size: u64,
45     /// unix mode of this inode. It may not have `S_IFDIR` and `S_IFREG` in case the original zip
46     /// doesn't have the information in the external_attributes fields. To test if this inode
47     /// is for a regular file or a directory, use `is_dir`.
48     pub mode: u32,
49     data: InodeDataData,
50 }
51 
52 type ZipIndex = usize;
53 
54 /// `InodeDataData` is the actual data (or a means to access the data) of the file or the directory
55 /// that an inode is representing. In case of a directory, this data is the hash table of the
56 /// directory entries. In case of a file, this data is the index of the file in `ZipArchive` which
57 /// can be used to retrieve `ZipFile` that provides access to the content of the file.
58 #[derive(Debug)]
59 enum InodeDataData {
60     Directory(HashMap<CString, DirectoryEntry>),
61     File(ZipIndex),
62 }
63 
64 #[derive(Debug, Clone)]
65 pub struct DirectoryEntry {
66     pub inode: Inode,
67     pub kind: InodeKind,
68 }
69 
70 #[derive(Debug, Clone, PartialEq, Eq, Copy)]
71 pub enum InodeKind {
72     Directory,
73     File,
74 }
75 
76 impl InodeData {
is_dir(&self) -> bool77     pub fn is_dir(&self) -> bool {
78         matches!(&self.data, InodeDataData::Directory(_))
79     }
80 
get_directory(&self) -> Option<&HashMap<CString, DirectoryEntry>>81     pub fn get_directory(&self) -> Option<&HashMap<CString, DirectoryEntry>> {
82         match &self.data {
83             InodeDataData::Directory(hash) => Some(hash),
84             _ => None,
85         }
86     }
87 
get_zip_index(&self) -> Option<ZipIndex>88     pub fn get_zip_index(&self) -> Option<ZipIndex> {
89         match &self.data {
90             InodeDataData::File(zip_index) => Some(*zip_index),
91             _ => None,
92         }
93     }
94 
95     // Below methods are used to construct the inode table when initializing the filesystem. Once
96     // the initialization is done, these are not used because this is a read-only filesystem.
97 
new_dir(mode: u32) -> InodeData98     fn new_dir(mode: u32) -> InodeData {
99         InodeData { mode, size: 0, data: InodeDataData::Directory(HashMap::new()) }
100     }
101 
new_file(zip_index: ZipIndex, mode: u32, zip_file: &zip::read::ZipFile) -> InodeData102     fn new_file(zip_index: ZipIndex, mode: u32, zip_file: &zip::read::ZipFile) -> InodeData {
103         InodeData { mode, size: zip_file.size(), data: InodeDataData::File(zip_index) }
104     }
105 
add_to_directory(&mut self, name: CString, entry: DirectoryEntry)106     fn add_to_directory(&mut self, name: CString, entry: DirectoryEntry) {
107         match &mut self.data {
108             InodeDataData::Directory(hashtable) => {
109                 let existing = hashtable.insert(name, entry);
110                 assert!(existing.is_none());
111             }
112             _ => {
113                 panic!("can't add a directory entry to a file inode");
114             }
115         }
116     }
117 }
118 
119 impl InodeTable {
120     /// Gets `InodeData` at a specific index.
get(&self, inode: Inode) -> Option<&InodeData>121     pub fn get(&self, inode: Inode) -> Option<&InodeData> {
122         match inode {
123             INVALID => None,
124             _ => self.table.get(inode as usize),
125         }
126     }
127 
get_mut(&mut self, inode: Inode) -> Option<&mut InodeData>128     fn get_mut(&mut self, inode: Inode) -> Option<&mut InodeData> {
129         match inode {
130             INVALID => None,
131             _ => self.table.get_mut(inode as usize),
132         }
133     }
134 
put(&mut self, data: InodeData) -> Inode135     fn put(&mut self, data: InodeData) -> Inode {
136         let inode = self.table.len() as Inode;
137         self.table.push(data);
138         inode
139     }
140 
141     /// Finds the inode number of a file named `name` in the `parent` inode. The `parent` inode
142     /// must exist and be a directory.
find(&self, parent: Inode, name: &CStr) -> Option<Inode>143     fn find(&self, parent: Inode, name: &CStr) -> Option<Inode> {
144         let data = self.get(parent).unwrap();
145         match data.get_directory().unwrap().get(name) {
146             Some(DirectoryEntry { inode, .. }) => Some(*inode),
147             _ => None,
148         }
149     }
150 
151     // Adds the inode `data` to the inode table and also links it to the `parent` inode as a file
152     // named `name`. The `parent` inode must exist and be a directory.
add(&mut self, parent: Inode, name: CString, data: InodeData) -> Inode153     fn add(&mut self, parent: Inode, name: CString, data: InodeData) -> Inode {
154         assert!(self.find(parent, &name).is_none());
155 
156         let kind = if data.is_dir() { InodeKind::Directory } else { InodeKind::File };
157         // Add the inode to the table
158         let inode = self.put(data);
159 
160         // ... and then register it to the directory of the parent inode
161         self.get_mut(parent).unwrap().add_to_directory(name, DirectoryEntry { inode, kind });
162         inode
163     }
164 
165     /// Constructs `InodeTable` from a zip archive `archive`.
from_zip<R: io::Read + io::Seek>( archive: &mut zip::ZipArchive<R>, ) -> Result<InodeTable>166     pub fn from_zip<R: io::Read + io::Seek>(
167         archive: &mut zip::ZipArchive<R>,
168     ) -> Result<InodeTable> {
169         let mut table = InodeTable { table: Vec::new() };
170 
171         // Add the inodes for the invalid and the root directory
172         assert_eq!(INVALID, table.put(InodeData::new_dir(0)));
173         assert_eq!(ROOT, table.put(InodeData::new_dir(DEFAULT_DIR_MODE)));
174 
175         // For each zip file in the archive, create an inode and add it to the table. If the file's
176         // parent directories don't have corresponding inodes in the table, handle them too.
177         for i in 0..archive.len() {
178             let file = archive.by_index(i)?;
179             let path = file
180                 .enclosed_name()
181                 .ok_or_else(|| anyhow!("{} is an invalid name", file.name()))?;
182             // TODO(jiyong): normalize this (e.g. a/b/c/../d -> a/b/d). We can't use
183             // fs::canonicalize as this is a non-existing path yet.
184 
185             let mut parent = ROOT;
186             let mut iter = path.iter().peekable();
187 
188             let mut file_mode = DEFAULT_FILE_MODE;
189             if path.starts_with("bin/") {
190                 // Allow files under bin to have execute permission, this enables payloads to bundle
191                 // additional binaries that they might want to execute.
192                 // An example of such binary is measure_io one used in the authfs performance tests.
193                 // More context available at b/265261525 and b/270955654.
194                 file_mode |= libc::S_IXUSR;
195             }
196 
197             while let Some(name) = iter.next() {
198                 // TODO(jiyong): remove this check by canonicalizing `path`
199                 if name == ".." {
200                     bail!(".. is not allowed");
201                 }
202 
203                 let is_leaf = iter.peek().is_none();
204                 let is_file = file.is_file() && is_leaf;
205 
206                 // The happy path; the inode for `name` is already in the `parent` inode. Move on
207                 // to the next path element.
208                 let name = CString::new(name.as_bytes()).unwrap();
209                 if let Some(found) = table.find(parent, &name) {
210                     parent = found;
211                     // Update the mode if this is a directory leaf.
212                     if !is_file && is_leaf {
213                         let mut inode = table.get_mut(parent).unwrap();
214                         inode.mode = file.unix_mode().unwrap_or(DEFAULT_DIR_MODE);
215                     }
216                     continue;
217                 }
218 
219                 // No inode found. Create a new inode and add it to the inode table.
220                 // At the moment of writing this comment the apk file doesn't specify any
221                 // permissions (apart from the ones on lib/), but it might change in the future.
222                 // TODO(b/270955654): should we control the file permissions ourselves?
223                 let inode = if is_file {
224                     InodeData::new_file(i, file.unix_mode().unwrap_or(file_mode), &file)
225                 } else if is_leaf {
226                     InodeData::new_dir(file.unix_mode().unwrap_or(DEFAULT_DIR_MODE))
227                 } else {
228                     InodeData::new_dir(DEFAULT_DIR_MODE)
229                 };
230                 let new = table.add(parent, name, inode);
231                 parent = new;
232             }
233         }
234         Ok(table)
235     }
236 }
237 
238 #[cfg(test)]
239 mod tests {
240     use crate::inode::*;
241     use std::io::{Cursor, Write};
242     use zip::write::FileOptions;
243 
244     // Creates an in-memory zip buffer, adds some files to it, and converts it to InodeTable
setup(add: fn(&mut zip::ZipWriter<&mut std::io::Cursor<Vec<u8>>>)) -> InodeTable245     fn setup(add: fn(&mut zip::ZipWriter<&mut std::io::Cursor<Vec<u8>>>)) -> InodeTable {
246         let mut buf: Cursor<Vec<u8>> = Cursor::new(Vec::new());
247         let mut writer = zip::ZipWriter::new(&mut buf);
248         add(&mut writer);
249         assert!(writer.finish().is_ok());
250         drop(writer);
251 
252         let zip = zip::ZipArchive::new(buf);
253         assert!(zip.is_ok());
254         let it = InodeTable::from_zip(&mut zip.unwrap());
255         assert!(it.is_ok());
256         it.unwrap()
257     }
258 
check_dir(it: &InodeTable, parent: Inode, name: &str) -> Inode259     fn check_dir(it: &InodeTable, parent: Inode, name: &str) -> Inode {
260         let name = CString::new(name.as_bytes()).unwrap();
261         let inode = it.find(parent, &name);
262         assert!(inode.is_some());
263         let inode = inode.unwrap();
264         let inode_data = it.get(inode);
265         assert!(inode_data.is_some());
266         let inode_data = inode_data.unwrap();
267         assert_eq!(0, inode_data.size);
268         assert!(inode_data.is_dir());
269         inode
270     }
271 
check_file<'a>(it: &'a InodeTable, parent: Inode, name: &str) -> &'a InodeData272     fn check_file<'a>(it: &'a InodeTable, parent: Inode, name: &str) -> &'a InodeData {
273         let name = CString::new(name.as_bytes()).unwrap();
274         let inode = it.find(parent, &name);
275         assert!(inode.is_some());
276         let inode = inode.unwrap();
277         let inode_data = it.get(inode);
278         assert!(inode_data.is_some());
279         let inode_data = inode_data.unwrap();
280         assert!(!inode_data.is_dir());
281         inode_data
282     }
283 
284     #[test]
empty_zip_has_two_inodes()285     fn empty_zip_has_two_inodes() {
286         let it = setup(|_| {});
287         assert_eq!(2, it.table.len());
288         assert!(it.get(INVALID).is_none());
289         assert!(it.get(ROOT).is_some());
290     }
291 
292     #[test]
one_file()293     fn one_file() {
294         let it = setup(|zip| {
295             zip.start_file("foo", FileOptions::default()).unwrap();
296             zip.write_all(b"0123456789").unwrap();
297         });
298         let inode_data = check_file(&it, ROOT, "foo");
299         assert_eq!(b"0123456789".len() as u64, inode_data.size);
300     }
301 
302     #[test]
one_dir()303     fn one_dir() {
304         let it = setup(|zip| {
305             zip.add_directory("foo", FileOptions::default()).unwrap();
306         });
307         let inode = check_dir(&it, ROOT, "foo");
308         // The directory doesn't have any entries
309         assert_eq!(0, it.get(inode).unwrap().get_directory().unwrap().len());
310     }
311 
312     #[test]
one_file_in_subdirs()313     fn one_file_in_subdirs() {
314         let it = setup(|zip| {
315             zip.start_file("a/b/c/d", FileOptions::default()).unwrap();
316             zip.write_all(b"0123456789").unwrap();
317         });
318 
319         assert_eq!(6, it.table.len());
320         let a = check_dir(&it, ROOT, "a");
321         let b = check_dir(&it, a, "b");
322         let c = check_dir(&it, b, "c");
323         let d = check_file(&it, c, "d");
324         assert_eq!(10, d.size);
325     }
326 
327     #[test]
complex_hierarchy()328     fn complex_hierarchy() {
329         // root/
330         //   a/
331         //    b1/
332         //    b2/
333         //      c1 (file)
334         //      c2/
335         //          d1 (file)
336         //          d2 (file)
337         //          d3 (file)
338         //  x/
339         //    y1 (file)
340         //    y2 (file)
341         //    y3/
342         //
343         //  foo (file)
344         //  bar (file)
345         let it = setup(|zip| {
346             let opt = FileOptions::default();
347             zip.add_directory("a/b1", opt).unwrap();
348 
349             zip.start_file("a/b2/c1", opt).unwrap();
350 
351             zip.start_file("a/b2/c2/d1", opt).unwrap();
352             zip.start_file("a/b2/c2/d2", opt).unwrap();
353             zip.start_file("a/b2/c2/d3", opt).unwrap();
354 
355             zip.start_file("x/y1", opt).unwrap();
356             zip.start_file("x/y2", opt).unwrap();
357             zip.add_directory("x/y3", opt).unwrap();
358 
359             zip.start_file("foo", opt).unwrap();
360             zip.start_file("bar", opt).unwrap();
361         });
362 
363         assert_eq!(16, it.table.len()); // 8 files, 6 dirs, and 2 (for root and the invalid inode)
364         let a = check_dir(&it, ROOT, "a");
365         let _b1 = check_dir(&it, a, "b1");
366         let b2 = check_dir(&it, a, "b2");
367         let _c1 = check_file(&it, b2, "c1");
368 
369         let c2 = check_dir(&it, b2, "c2");
370         let _d1 = check_file(&it, c2, "d1");
371         let _d2 = check_file(&it, c2, "d3");
372         let _d3 = check_file(&it, c2, "d3");
373 
374         let x = check_dir(&it, ROOT, "x");
375         let _y1 = check_file(&it, x, "y1");
376         let _y2 = check_file(&it, x, "y2");
377         let _y3 = check_dir(&it, x, "y3");
378 
379         let _foo = check_file(&it, ROOT, "foo");
380         let _bar = check_file(&it, ROOT, "bar");
381     }
382 
383     #[test]
file_size()384     fn file_size() {
385         let it = setup(|zip| {
386             let opt = FileOptions::default();
387             zip.start_file("empty", opt).unwrap();
388 
389             zip.start_file("10bytes", opt).unwrap();
390             zip.write_all(&[0; 10]).unwrap();
391 
392             zip.start_file("1234bytes", opt).unwrap();
393             zip.write_all(&[0; 1234]).unwrap();
394 
395             zip.start_file("2^20bytes", opt).unwrap();
396             zip.write_all(&[0; 2 << 20]).unwrap();
397         });
398 
399         let f = check_file(&it, ROOT, "empty");
400         assert_eq!(0, f.size);
401 
402         let f = check_file(&it, ROOT, "10bytes");
403         assert_eq!(10, f.size);
404 
405         let f = check_file(&it, ROOT, "1234bytes");
406         assert_eq!(1234, f.size);
407 
408         let f = check_file(&it, ROOT, "2^20bytes");
409         assert_eq!(2 << 20, f.size);
410     }
411 
412     #[test]
rejects_invalid_paths()413     fn rejects_invalid_paths() {
414         let invalid_paths = [
415             "a/../../b",   // escapes the root
416             "a/..",        // escapes the root
417             "a/../../b/c", // escape the root
418             "a/b/../c",    // doesn't escape the root, but not normalized
419         ];
420         for path in invalid_paths.iter() {
421             let mut buf: Cursor<Vec<u8>> = Cursor::new(Vec::new());
422             let mut writer = zip::ZipWriter::new(&mut buf);
423             writer.start_file(*path, FileOptions::default()).unwrap();
424             assert!(writer.finish().is_ok());
425             drop(writer);
426 
427             let zip = zip::ZipArchive::new(buf);
428             assert!(zip.is_ok());
429             let it = InodeTable::from_zip(&mut zip.unwrap());
430             assert!(it.is_err());
431         }
432     }
433 }
434