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