blob: 9411759a50e6cc9e0bfcac55abe83ced61b8ca7a [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 */
16
17//! `zipfuse` is a FUSE filesystem for zip archives. It provides transparent access to the files
18//! in a zip archive. This filesystem does not supporting writing files back to the zip archive.
19//! The filesystem has to be mounted read only.
20
21mod inode;
22
Alan Stokes60f82202022-10-07 16:40:07 +010023use anyhow::{Context as AnyhowContext, Result};
Jiyong Park331d1ea2021-05-10 11:01:23 +090024use clap::{App, Arg};
25use fuse::filesystem::*;
26use fuse::mount::*;
Alan Stokes60f82202022-10-07 16:40:07 +010027use rustutils::system_properties;
Jiyong Park331d1ea2021-05-10 11:01:23 +090028use std::collections::HashMap;
29use std::convert::TryFrom;
Jiyong Park851f68a2021-05-11 21:41:25 +090030use std::ffi::{CStr, CString};
Jiyong Park331d1ea2021-05-10 11:01:23 +090031use std::fs::{File, OpenOptions};
32use std::io;
33use std::io::Read;
Jiyong Park63a95cf2021-05-13 19:20:30 +090034use std::mem::size_of;
Jiyong Park331d1ea2021-05-10 11:01:23 +090035use std::os::unix::io::AsRawFd;
36use std::path::Path;
37use std::sync::Mutex;
38
39use crate::inode::{DirectoryEntry, Inode, InodeData, InodeKind, InodeTable};
40
41fn main() -> Result<()> {
42 let matches = App::new("zipfuse")
Jiyong Park6a762db2021-05-31 14:00:52 +090043 .arg(
44 Arg::with_name("options")
Jeff Vander Stoepa8dc2712022-07-29 02:33:45 +020045 .short('o')
Jiyong Park6a762db2021-05-31 14:00:52 +090046 .takes_value(true)
47 .required(false)
Chris Wailes68c39f82021-07-27 16:03:44 -070048 .help("Comma separated list of mount options"),
Jiyong Park6a762db2021-05-31 14:00:52 +090049 )
Andrew Scull3854e402022-07-04 12:10:20 +000050 .arg(
51 Arg::with_name("noexec")
52 .long("noexec")
53 .takes_value(false)
54 .help("Disallow the execution of binary files"),
55 )
Alan Stokes60f82202022-10-07 16:40:07 +010056 .arg(
57 Arg::with_name("readyprop")
58 .short('p')
59 .takes_value(true)
60 .help("Specify a property to be set when mount is ready"),
61 )
Jiyong Park331d1ea2021-05-10 11:01:23 +090062 .arg(Arg::with_name("ZIPFILE").required(true))
63 .arg(Arg::with_name("MOUNTPOINT").required(true))
64 .get_matches();
65
66 let zip_file = matches.value_of("ZIPFILE").unwrap().as_ref();
67 let mount_point = matches.value_of("MOUNTPOINT").unwrap().as_ref();
Jiyong Park6a762db2021-05-31 14:00:52 +090068 let options = matches.value_of("options");
Andrew Scull3854e402022-07-04 12:10:20 +000069 let noexec = matches.is_present("noexec");
Alan Stokes60f82202022-10-07 16:40:07 +010070 let ready_prop = matches.value_of("readyprop");
71 run_fuse(zip_file, mount_point, options, noexec, ready_prop)?;
Jiyong Park331d1ea2021-05-10 11:01:23 +090072 Ok(())
73}
74
75/// Runs a fuse filesystem by mounting `zip_file` on `mount_point`.
Andrew Scull3854e402022-07-04 12:10:20 +000076pub fn run_fuse(
77 zip_file: &Path,
78 mount_point: &Path,
79 extra_options: Option<&str>,
80 noexec: bool,
Alan Stokes60f82202022-10-07 16:40:07 +010081 ready_prop: Option<&str>,
Andrew Scull3854e402022-07-04 12:10:20 +000082) -> Result<()> {
Jiyong Park331d1ea2021-05-10 11:01:23 +090083 const MAX_READ: u32 = 1 << 20; // TODO(jiyong): tune this
84 const MAX_WRITE: u32 = 1 << 13; // This is a read-only filesystem
85
86 let dev_fuse = OpenOptions::new().read(true).write(true).open("/dev/fuse")?;
87
Jiyong Park6a762db2021-05-31 14:00:52 +090088 let mut mount_options = vec![
89 MountOption::FD(dev_fuse.as_raw_fd()),
90 MountOption::RootMode(libc::S_IFDIR | libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH),
91 MountOption::AllowOther,
92 MountOption::UserId(0),
93 MountOption::GroupId(0),
94 MountOption::MaxRead(MAX_READ),
95 ];
96 if let Some(value) = extra_options {
97 mount_options.push(MountOption::Extra(value));
98 }
99
Andrew Scull3854e402022-07-04 12:10:20 +0000100 let mut mount_flags = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_RDONLY;
101 if noexec {
102 mount_flags |= libc::MS_NOEXEC;
103 }
104
105 fuse::mount(mount_point, "zipfuse", mount_flags, &mount_options)?;
Alan Stokes60f82202022-10-07 16:40:07 +0100106
107 if let Some(property_name) = ready_prop {
108 system_properties::write(property_name, "1").context("Failed to set readyprop")?;
109 }
110
Victor Hsieh58a5e9b2022-03-09 21:57:26 +0000111 let mut config = fuse::FuseConfig::new();
112 config.dev_fuse(dev_fuse).max_write(MAX_WRITE).max_read(MAX_READ);
113 Ok(config.enter_message_loop(ZipFuse::new(zip_file)?)?)
Jiyong Park331d1ea2021-05-10 11:01:23 +0900114}
115
116struct ZipFuse {
117 zip_archive: Mutex<zip::ZipArchive<File>>,
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900118 raw_file: Mutex<File>,
Jiyong Park331d1ea2021-05-10 11:01:23 +0900119 inode_table: InodeTable,
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900120 open_files: Mutex<HashMap<Handle, OpenFile>>,
Jiyong Park331d1ea2021-05-10 11:01:23 +0900121 open_dirs: Mutex<HashMap<Handle, OpenDirBuf>>,
122}
123
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900124/// Represents a [`ZipFile`] that is opened.
125struct OpenFile {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900126 open_count: u32, // multiple opens share the buf because this is a read-only filesystem
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900127 content: OpenFileContent,
128}
129
130/// Holds the content of a [`ZipFile`]. Depending on whether it is compressed or not, the
131/// entire content is stored, or only the zip index is stored.
132enum OpenFileContent {
133 Compressed(Box<[u8]>),
134 Uncompressed(usize), // zip index
Jiyong Park331d1ea2021-05-10 11:01:23 +0900135}
136
137/// Holds the directory entries in a directory opened by [`opendir`].
138struct OpenDirBuf {
139 open_count: u32,
140 buf: Box<[(CString, DirectoryEntry)]>,
141}
142
143type Handle = u64;
144
145fn ebadf() -> io::Error {
146 io::Error::from_raw_os_error(libc::EBADF)
147}
148
149fn timeout_max() -> std::time::Duration {
150 std::time::Duration::new(u64::MAX, 1_000_000_000 - 1)
151}
152
153impl ZipFuse {
154 fn new(zip_file: &Path) -> Result<ZipFuse> {
155 // TODO(jiyong): Use O_DIRECT to avoid double caching.
156 // `.custom_flags(nix::fcntl::OFlag::O_DIRECT.bits())` currently doesn't work.
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900157 let f = File::open(zip_file)?;
Jiyong Park331d1ea2021-05-10 11:01:23 +0900158 let mut z = zip::ZipArchive::new(f)?;
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900159 // Open the same file again so that we can directly access it when accessing
160 // uncompressed zip_file entries in it. `ZipFile` doesn't implement `Seek`.
161 let raw_file = File::open(zip_file)?;
Jiyong Park331d1ea2021-05-10 11:01:23 +0900162 let it = InodeTable::from_zip(&mut z)?;
163 Ok(ZipFuse {
164 zip_archive: Mutex::new(z),
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900165 raw_file: Mutex::new(raw_file),
Jiyong Park331d1ea2021-05-10 11:01:23 +0900166 inode_table: it,
167 open_files: Mutex::new(HashMap::new()),
168 open_dirs: Mutex::new(HashMap::new()),
169 })
170 }
171
172 fn find_inode(&self, inode: Inode) -> io::Result<&InodeData> {
173 self.inode_table.get(inode).ok_or_else(ebadf)
174 }
175
Jiyong Parkd5df9562021-05-13 00:50:23 +0900176 // TODO(jiyong) remove this. Right now this is needed to do the nlink_t to u64 conversion below
177 // on aosp_x86_64 target. That however is a useless conversion on other targets.
178 #[allow(clippy::useless_conversion)]
Jiyong Park331d1ea2021-05-10 11:01:23 +0900179 fn stat_from(&self, inode: Inode) -> io::Result<libc::stat64> {
180 let inode_data = self.find_inode(inode)?;
181 let mut st = unsafe { std::mem::MaybeUninit::<libc::stat64>::zeroed().assume_init() };
182 st.st_dev = 0;
Jiyong Parkd5df9562021-05-13 00:50:23 +0900183 st.st_nlink = if let Some(directory) = inode_data.get_directory() {
184 (2 + directory.len() as libc::nlink_t).into()
Jiyong Park331d1ea2021-05-10 11:01:23 +0900185 } else {
186 1
187 };
188 st.st_ino = inode;
189 st.st_mode = if inode_data.is_dir() { libc::S_IFDIR } else { libc::S_IFREG };
190 st.st_mode |= inode_data.mode;
191 st.st_uid = 0;
192 st.st_gid = 0;
193 st.st_size = i64::try_from(inode_data.size).unwrap_or(i64::MAX);
194 Ok(st)
195 }
196}
197
198impl fuse::filesystem::FileSystem for ZipFuse {
199 type Inode = Inode;
200 type Handle = Handle;
201 type DirIter = DirIter;
202
203 fn init(&self, _capable: FsOptions) -> std::io::Result<FsOptions> {
204 // The default options added by the fuse crate are fine. We don't have additional options.
205 Ok(FsOptions::empty())
206 }
207
208 fn lookup(&self, _ctx: Context, parent: Self::Inode, name: &CStr) -> io::Result<Entry> {
209 let inode = self.find_inode(parent)?;
210 let directory = inode.get_directory().ok_or_else(ebadf)?;
Jiyong Park331d1ea2021-05-10 11:01:23 +0900211 let entry = directory.get(name);
212 match entry {
213 Some(e) => Ok(Entry {
214 inode: e.inode,
215 generation: 0,
216 attr: self.stat_from(e.inode)?,
217 attr_timeout: timeout_max(), // this is a read-only fs
218 entry_timeout: timeout_max(),
219 }),
220 _ => Err(io::Error::from_raw_os_error(libc::ENOENT)),
221 }
222 }
223
224 fn getattr(
225 &self,
226 _ctx: Context,
227 inode: Self::Inode,
228 _handle: Option<Self::Handle>,
229 ) -> io::Result<(libc::stat64, std::time::Duration)> {
230 let st = self.stat_from(inode)?;
231 Ok((st, timeout_max()))
232 }
233
234 fn open(
235 &self,
236 _ctx: Context,
237 inode: Self::Inode,
238 _flags: u32,
239 ) -> io::Result<(Option<Self::Handle>, fuse::filesystem::OpenOptions)> {
240 let mut open_files = self.open_files.lock().unwrap();
241 let handle = inode as Handle;
242
243 // If the file is already opened, just increase the reference counter. If not, read the
244 // entire file content to the buffer. When `read` is called, a portion of the buffer is
245 // copied to the kernel.
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900246 if let Some(file) = open_files.get_mut(&handle) {
247 if file.open_count == 0 {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900248 return Err(ebadf());
249 }
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900250 file.open_count += 1;
Jiyong Park331d1ea2021-05-10 11:01:23 +0900251 } else {
252 let inode_data = self.find_inode(inode)?;
253 let zip_index = inode_data.get_zip_index().ok_or_else(ebadf)?;
254 let mut zip_archive = self.zip_archive.lock().unwrap();
255 let mut zip_file = zip_archive.by_index(zip_index)?;
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900256 let content = match zip_file.compression() {
257 zip::CompressionMethod::Stored => OpenFileContent::Uncompressed(zip_index),
258 _ => {
259 if let Some(mode) = zip_file.unix_mode() {
260 let is_reg_file = zip_file.is_file();
261 let is_executable =
262 mode & (libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH) != 0;
263 if is_reg_file && is_executable {
264 log::warn!(
265 "Executable file {:?} is stored compressed. Consider \
266 storing it uncompressed to save memory",
267 zip_file.mangled_name()
268 );
269 }
270 }
271 let mut buf = Vec::with_capacity(inode_data.size as usize);
272 zip_file.read_to_end(&mut buf)?;
273 OpenFileContent::Compressed(buf.into_boxed_slice())
274 }
275 };
276 open_files.insert(handle, OpenFile { open_count: 1, content });
Jiyong Park331d1ea2021-05-10 11:01:23 +0900277 }
278 // Note: we don't return `DIRECT_IO` here, because then applications wouldn't be able to
279 // mmap the files.
280 Ok((Some(handle), fuse::filesystem::OpenOptions::empty()))
281 }
282
283 fn release(
284 &self,
285 _ctx: Context,
286 inode: Self::Inode,
287 _flags: u32,
288 _handle: Self::Handle,
289 _flush: bool,
290 _flock_release: bool,
291 _lock_owner: Option<u64>,
292 ) -> io::Result<()> {
293 // Releases the buffer for the `handle` when it is opened for nobody. While this is good
294 // for saving memory, this has a performance implication because we need to decompress
295 // again when the same file is opened in the future.
296 let mut open_files = self.open_files.lock().unwrap();
297 let handle = inode as Handle;
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900298 if let Some(file) = open_files.get_mut(&handle) {
299 if file.open_count.checked_sub(1).ok_or_else(ebadf)? == 0 {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900300 open_files.remove(&handle);
301 }
302 Ok(())
303 } else {
304 Err(ebadf())
305 }
306 }
307
308 fn read<W: io::Write + ZeroCopyWriter>(
309 &self,
310 _ctx: Context,
311 _inode: Self::Inode,
312 handle: Self::Handle,
313 mut w: W,
314 size: u32,
315 offset: u64,
316 _lock_owner: Option<u64>,
317 _flags: u32,
318 ) -> io::Result<usize> {
319 let open_files = self.open_files.lock().unwrap();
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900320 let file = open_files.get(&handle).ok_or_else(ebadf)?;
321 if file.open_count == 0 {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900322 return Err(ebadf());
323 }
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900324 Ok(match &file.content {
325 OpenFileContent::Uncompressed(zip_index) => {
326 let mut zip_archive = self.zip_archive.lock().unwrap();
327 let zip_file = zip_archive.by_index(*zip_index)?;
328 let start = zip_file.data_start() + offset;
329 let remaining_size = zip_file.size() - offset;
330 let size = std::cmp::min(remaining_size, size.into());
331
332 let mut raw_file = self.raw_file.lock().unwrap();
333 w.write_from(&mut raw_file, size as usize, start)?
334 }
335 OpenFileContent::Compressed(buf) => {
336 let start = offset as usize;
337 let end = start + size as usize;
338 let end = std::cmp::min(end, buf.len());
339 w.write(&buf[start..end])?
340 }
341 })
Jiyong Park331d1ea2021-05-10 11:01:23 +0900342 }
343
344 fn opendir(
345 &self,
346 _ctx: Context,
347 inode: Self::Inode,
348 _flags: u32,
349 ) -> io::Result<(Option<Self::Handle>, fuse::filesystem::OpenOptions)> {
350 let mut open_dirs = self.open_dirs.lock().unwrap();
351 let handle = inode as Handle;
352 if let Some(odb) = open_dirs.get_mut(&handle) {
353 if odb.open_count == 0 {
354 return Err(ebadf());
355 }
356 odb.open_count += 1;
357 } else {
358 let inode_data = self.find_inode(inode)?;
359 let directory = inode_data.get_directory().ok_or_else(ebadf)?;
360 let mut buf: Vec<(CString, DirectoryEntry)> = Vec::with_capacity(directory.len());
361 for (name, dir_entry) in directory.iter() {
362 let name = CString::new(name.as_bytes()).unwrap();
363 buf.push((name, dir_entry.clone()));
364 }
365 open_dirs.insert(handle, OpenDirBuf { open_count: 1, buf: buf.into_boxed_slice() });
366 }
Jiyong Park63a95cf2021-05-13 19:20:30 +0900367 Ok((Some(handle), fuse::filesystem::OpenOptions::CACHE_DIR))
Jiyong Park331d1ea2021-05-10 11:01:23 +0900368 }
369
370 fn releasedir(
371 &self,
372 _ctx: Context,
373 inode: Self::Inode,
374 _flags: u32,
375 _handle: Self::Handle,
376 ) -> io::Result<()> {
377 let mut open_dirs = self.open_dirs.lock().unwrap();
378 let handle = inode as Handle;
379 if let Some(odb) = open_dirs.get_mut(&handle) {
380 if odb.open_count.checked_sub(1).ok_or_else(ebadf)? == 0 {
381 open_dirs.remove(&handle);
382 }
383 Ok(())
384 } else {
385 Err(ebadf())
386 }
387 }
388
389 fn readdir(
390 &self,
391 _ctx: Context,
392 inode: Self::Inode,
393 _handle: Self::Handle,
394 size: u32,
395 offset: u64,
396 ) -> io::Result<Self::DirIter> {
397 let open_dirs = self.open_dirs.lock().unwrap();
398 let handle = inode as Handle;
399 let odb = open_dirs.get(&handle).ok_or_else(ebadf)?;
400 if odb.open_count == 0 {
401 return Err(ebadf());
402 }
403 let buf = &odb.buf;
404 let start = offset as usize;
Jiyong Park63a95cf2021-05-13 19:20:30 +0900405
406 // Estimate the size of each entry will take space in the buffer. See
407 // external/crosvm/fuse/src/server.rs#add_dirent
408 let mut estimate: usize = 0; // estimated number of bytes we will be writing
409 let mut end = start; // index in `buf`
410 while estimate < size as usize && end < buf.len() {
411 let dirent_size = size_of::<fuse::sys::Dirent>();
412 let name_size = buf[end].0.to_bytes().len();
413 estimate += (dirent_size + name_size + 7) & !7; // round to 8 byte boundary
414 end += 1;
415 }
416
Jiyong Park331d1ea2021-05-10 11:01:23 +0900417 let mut new_buf = Vec::with_capacity(end - start);
418 // The portion of `buf` is *copied* to the iterator. This is not ideal, but inevitable
419 // because the `name` field in `fuse::filesystem::DirEntry` is `&CStr` not `CString`.
420 new_buf.extend_from_slice(&buf[start..end]);
421 Ok(DirIter { inner: new_buf, offset, cur: 0 })
422 }
423}
424
425struct DirIter {
426 inner: Vec<(CString, DirectoryEntry)>,
427 offset: u64, // the offset where this iterator begins. `next` doesn't change this.
428 cur: usize, // the current index in `inner`. `next` advances this.
429}
430
431impl fuse::filesystem::DirectoryIterator for DirIter {
432 fn next(&mut self) -> Option<fuse::filesystem::DirEntry> {
433 if self.cur >= self.inner.len() {
434 return None;
435 }
436
437 let (name, entry) = &self.inner[self.cur];
438 self.cur += 1;
439 Some(fuse::filesystem::DirEntry {
440 ino: entry.inode as libc::ino64_t,
441 offset: self.offset + self.cur as u64,
442 type_: match entry.kind {
443 InodeKind::Directory => libc::DT_DIR.into(),
444 InodeKind::File => libc::DT_REG.into(),
445 },
446 name,
447 })
448 }
449}
450
451#[cfg(test)]
452mod tests {
453 use anyhow::{bail, Result};
454 use nix::sys::statfs::{statfs, FsType};
Jiyong Park63a95cf2021-05-13 19:20:30 +0900455 use std::collections::BTreeSet;
Jiyong Park331d1ea2021-05-10 11:01:23 +0900456 use std::fs;
457 use std::fs::File;
458 use std::io::Write;
459 use std::path::{Path, PathBuf};
460 use std::time::{Duration, Instant};
461 use zip::write::FileOptions;
462
463 #[cfg(not(target_os = "android"))]
Andrew Scull3854e402022-07-04 12:10:20 +0000464 fn start_fuse(zip_path: &Path, mnt_path: &Path, noexec: bool) {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900465 let zip_path = PathBuf::from(zip_path);
466 let mnt_path = PathBuf::from(mnt_path);
467 std::thread::spawn(move || {
Andrew Scull3854e402022-07-04 12:10:20 +0000468 crate::run_fuse(&zip_path, &mnt_path, None, noexec).unwrap();
Jiyong Park331d1ea2021-05-10 11:01:23 +0900469 });
470 }
471
472 #[cfg(target_os = "android")]
Andrew Scull3854e402022-07-04 12:10:20 +0000473 fn start_fuse(zip_path: &Path, mnt_path: &Path, noexec: bool) {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900474 // Note: for some unknown reason, running a thread to serve fuse doesn't work on Android.
475 // Explicitly spawn a zipfuse process instead.
476 // TODO(jiyong): fix this
Andrew Scull3854e402022-07-04 12:10:20 +0000477 let noexec = if noexec { "--noexec" } else { "" };
Jiyong Park331d1ea2021-05-10 11:01:23 +0900478 assert!(std::process::Command::new("sh")
479 .arg("-c")
Andrew Scull3854e402022-07-04 12:10:20 +0000480 .arg(format!(
481 "/data/local/tmp/zipfuse {} {} {}",
482 noexec,
483 zip_path.display(),
484 mnt_path.display()
485 ))
Jiyong Park331d1ea2021-05-10 11:01:23 +0900486 .spawn()
487 .is_ok());
488 }
489
490 fn wait_for_mount(mount_path: &Path) -> Result<()> {
491 let start_time = Instant::now();
492 const POLL_INTERVAL: Duration = Duration::from_millis(50);
493 const TIMEOUT: Duration = Duration::from_secs(10);
494 const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
495 loop {
496 if statfs(mount_path)?.filesystem_type() == FUSE_SUPER_MAGIC {
497 break;
498 }
499
500 if start_time.elapsed() > TIMEOUT {
501 bail!("Time out mounting zipfuse");
502 }
503 std::thread::sleep(POLL_INTERVAL);
504 }
505 Ok(())
506 }
507
508 // Creates a zip file, adds some files to the zip file, mounts it using zipfuse, runs the check
509 // routine, and finally unmounts.
510 fn run_test(add: fn(&mut zip::ZipWriter<File>), check: fn(&std::path::Path)) {
Andrew Scull3854e402022-07-04 12:10:20 +0000511 run_test_noexec(false, add, check);
512 }
513
514 fn run_test_noexec(
515 noexec: bool,
516 add: fn(&mut zip::ZipWriter<File>),
517 check: fn(&std::path::Path),
518 ) {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900519 // Create an empty zip file
520 let test_dir = tempfile::TempDir::new().unwrap();
521 let zip_path = test_dir.path().join("test.zip");
522 let zip = File::create(&zip_path);
523 assert!(zip.is_ok());
524 let mut zip = zip::ZipWriter::new(zip.unwrap());
525
526 // Let test users add files/dirs to the zip file
527 add(&mut zip);
528 assert!(zip.finish().is_ok());
529 drop(zip);
530
531 // Mount the zip file on the "mnt" dir using zipfuse.
532 let mnt_path = test_dir.path().join("mnt");
533 assert!(fs::create_dir(&mnt_path).is_ok());
534
Andrew Scull3854e402022-07-04 12:10:20 +0000535 start_fuse(&zip_path, &mnt_path, noexec);
Jiyong Park331d1ea2021-05-10 11:01:23 +0900536
537 let mnt_path = test_dir.path().join("mnt");
538 // Give some time for the fuse to boot up
539 assert!(wait_for_mount(&mnt_path).is_ok());
540 // Run the check routine, and do the clean up.
541 check(&mnt_path);
542 assert!(nix::mount::umount2(&mnt_path, nix::mount::MntFlags::empty()).is_ok());
543 }
544
545 fn check_file(root: &Path, file: &str, content: &[u8]) {
546 let path = root.join(file);
547 assert!(path.exists());
548
549 let metadata = fs::metadata(&path);
550 assert!(metadata.is_ok());
551
552 let metadata = metadata.unwrap();
553 assert!(metadata.is_file());
554 assert_eq!(content.len(), metadata.len() as usize);
555
556 let read_data = fs::read(&path);
557 assert!(read_data.is_ok());
558 assert_eq!(content, read_data.unwrap().as_slice());
559 }
560
Jiyong Park63a95cf2021-05-13 19:20:30 +0900561 fn check_dir<S: AsRef<str>>(root: &Path, dir: &str, files: &[S], dirs: &[S]) {
Jiyong Park331d1ea2021-05-10 11:01:23 +0900562 let dir_path = root.join(dir);
563 assert!(dir_path.exists());
564
565 let metadata = fs::metadata(&dir_path);
566 assert!(metadata.is_ok());
567
568 let metadata = metadata.unwrap();
569 assert!(metadata.is_dir());
570
571 let iter = fs::read_dir(&dir_path);
572 assert!(iter.is_ok());
573
574 let iter = iter.unwrap();
Jiyong Park63a95cf2021-05-13 19:20:30 +0900575 let mut actual_files = BTreeSet::new();
576 let mut actual_dirs = BTreeSet::new();
Jiyong Park331d1ea2021-05-10 11:01:23 +0900577 for de in iter {
578 let entry = de.unwrap();
579 let path = entry.path();
580 if path.is_dir() {
581 actual_dirs.insert(path.strip_prefix(&dir_path).unwrap().to_path_buf());
582 } else {
583 actual_files.insert(path.strip_prefix(&dir_path).unwrap().to_path_buf());
584 }
585 }
Jiyong Park63a95cf2021-05-13 19:20:30 +0900586 let expected_files: BTreeSet<PathBuf> =
587 files.iter().map(|s| PathBuf::from(s.as_ref())).collect();
588 let expected_dirs: BTreeSet<PathBuf> =
589 dirs.iter().map(|s| PathBuf::from(s.as_ref())).collect();
Jiyong Park331d1ea2021-05-10 11:01:23 +0900590
591 assert_eq!(expected_files, actual_files);
592 assert_eq!(expected_dirs, actual_dirs);
593 }
594
595 #[test]
596 fn empty() {
597 run_test(
598 |_| {},
599 |root| {
Jiyong Park63a95cf2021-05-13 19:20:30 +0900600 check_dir::<String>(root, "", &[], &[]);
Jiyong Park331d1ea2021-05-10 11:01:23 +0900601 },
602 );
603 }
604
605 #[test]
606 fn single_file() {
607 run_test(
608 |zip| {
609 zip.start_file("foo", FileOptions::default()).unwrap();
610 zip.write_all(b"0123456789").unwrap();
611 },
612 |root| {
613 check_dir(root, "", &["foo"], &[]);
614 check_file(root, "foo", b"0123456789");
615 },
616 );
617 }
618
619 #[test]
Andrew Scull3854e402022-07-04 12:10:20 +0000620 fn noexec() {
621 fn add_executable(zip: &mut zip::ZipWriter<File>) {
622 zip.start_file("executable", FileOptions::default().unix_permissions(0o755)).unwrap();
623 }
624
625 // Executables can be run when not mounting with noexec.
626 run_test(add_executable, |root| {
627 let res = std::process::Command::new(root.join("executable")).status();
628 res.unwrap();
629 });
630
631 // Mounting with noexec results in permissions denial when running an executable.
632 let noexec = true;
633 run_test_noexec(noexec, add_executable, |root| {
634 let res = std::process::Command::new(root.join("executable")).status();
635 assert!(matches!(res.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied));
636 });
637 }
638
639 #[test]
Jiyong Park331d1ea2021-05-10 11:01:23 +0900640 fn single_dir() {
641 run_test(
642 |zip| {
643 zip.add_directory("dir", FileOptions::default()).unwrap();
644 },
645 |root| {
646 check_dir(root, "", &[], &["dir"]);
Jiyong Park63a95cf2021-05-13 19:20:30 +0900647 check_dir::<String>(root, "dir", &[], &[]);
Jiyong Park331d1ea2021-05-10 11:01:23 +0900648 },
649 );
650 }
651
652 #[test]
653 fn complex_hierarchy() {
654 // root/
655 // a/
656 // b1/
657 // b2/
658 // c1 (file)
659 // c2/
660 // d1 (file)
661 // d2 (file)
662 // d3 (file)
663 // x/
664 // y1 (file)
665 // y2 (file)
666 // y3/
667 //
668 // foo (file)
669 // bar (file)
670 run_test(
671 |zip| {
672 let opt = FileOptions::default();
673 zip.add_directory("a/b1", opt).unwrap();
674
675 zip.start_file("a/b2/c1", opt).unwrap();
676
677 zip.start_file("a/b2/c2/d1", opt).unwrap();
678 zip.start_file("a/b2/c2/d2", opt).unwrap();
679 zip.start_file("a/b2/c2/d3", opt).unwrap();
680
681 zip.start_file("x/y1", opt).unwrap();
682 zip.start_file("x/y2", opt).unwrap();
683 zip.add_directory("x/y3", opt).unwrap();
684
685 zip.start_file("foo", opt).unwrap();
686 zip.start_file("bar", opt).unwrap();
687 },
688 |root| {
689 check_dir(root, "", &["foo", "bar"], &["a", "x"]);
690 check_dir(root, "a", &[], &["b1", "b2"]);
Jiyong Park63a95cf2021-05-13 19:20:30 +0900691 check_dir::<String>(root, "a/b1", &[], &[]);
Jiyong Park331d1ea2021-05-10 11:01:23 +0900692 check_dir(root, "a/b2", &["c1"], &["c2"]);
693 check_dir(root, "a/b2/c2", &["d1", "d2", "d3"], &[]);
694 check_dir(root, "x", &["y1", "y2"], &["y3"]);
Jiyong Park63a95cf2021-05-13 19:20:30 +0900695 check_dir::<String>(root, "x/y3", &[], &[]);
Jiyong Park331d1ea2021-05-10 11:01:23 +0900696 check_file(root, "a/b2/c1", &[]);
697 check_file(root, "a/b2/c2/d1", &[]);
698 check_file(root, "a/b2/c2/d2", &[]);
699 check_file(root, "a/b2/c2/d3", &[]);
700 check_file(root, "x/y1", &[]);
701 check_file(root, "x/y2", &[]);
702 check_file(root, "foo", &[]);
703 check_file(root, "bar", &[]);
704 },
705 );
706 }
707
708 #[test]
709 fn large_file() {
710 run_test(
711 |zip| {
712 let data = vec![10; 2 << 20];
713 zip.start_file("foo", FileOptions::default()).unwrap();
714 zip.write_all(&data).unwrap();
715 },
716 |root| {
717 let data = vec![10; 2 << 20];
718 check_file(root, "foo", &data);
719 },
720 );
721 }
Jiyong Park63a95cf2021-05-13 19:20:30 +0900722
723 #[test]
724 fn large_dir() {
725 const NUM_FILES: usize = 1 << 10;
726 run_test(
727 |zip| {
728 let opt = FileOptions::default();
729 // create 1K files. Each file has a name of length 100. So total size is at least
730 // 100KB, which is bigger than the readdir buffer size of 4K.
731 for i in 0..NUM_FILES {
732 zip.start_file(format!("dir/{:0100}", i), opt).unwrap();
733 }
734 },
735 |root| {
736 let dirs_expected: Vec<_> = (0..NUM_FILES).map(|i| format!("{:0100}", i)).collect();
737 check_dir(
738 root,
739 "dir",
740 dirs_expected.iter().map(|s| s.as_str()).collect::<Vec<&str>>().as_slice(),
741 &[],
742 );
743 },
744 );
745 }
Jiyong Parkd40f7bb2021-05-17 10:55:56 +0900746
Jiyong Parke6587ca2021-05-17 14:42:23 +0900747 fn run_fuse_and_check_test_zip(test_dir: &Path, zip_path: &Path) {
748 let mnt_path = test_dir.join("mnt");
Jiyong Parkd40f7bb2021-05-17 10:55:56 +0900749 assert!(fs::create_dir(&mnt_path).is_ok());
750
Andrew Scull3854e402022-07-04 12:10:20 +0000751 let noexec = false;
752 start_fuse(zip_path, &mnt_path, noexec);
Jiyong Parkd40f7bb2021-05-17 10:55:56 +0900753
754 // Give some time for the fuse to boot up
755 assert!(wait_for_mount(&mnt_path).is_ok());
756
757 check_dir(&mnt_path, "", &[], &["dir"]);
758 check_dir(&mnt_path, "dir", &["file1", "file2"], &[]);
759 check_file(&mnt_path, "dir/file1", include_bytes!("../testdata/dir/file1"));
760 check_file(&mnt_path, "dir/file2", include_bytes!("../testdata/dir/file2"));
761 assert!(nix::mount::umount2(&mnt_path, nix::mount::MntFlags::empty()).is_ok());
762 }
Jiyong Parke6587ca2021-05-17 14:42:23 +0900763
764 #[test]
765 fn supports_deflate() {
766 let test_dir = tempfile::TempDir::new().unwrap();
767 let zip_path = test_dir.path().join("test.zip");
768 let mut zip_file = File::create(&zip_path).unwrap();
769 zip_file.write_all(include_bytes!("../testdata/test.zip")).unwrap();
770
Chris Wailes68c39f82021-07-27 16:03:44 -0700771 run_fuse_and_check_test_zip(test_dir.path(), &zip_path);
Jiyong Parke6587ca2021-05-17 14:42:23 +0900772 }
773
Jiyong Parkf5ff33c2021-08-30 22:32:19 +0900774 #[test]
775 fn supports_store() {
776 run_test(
777 |zip| {
778 let data = vec![10; 2 << 20];
779 zip.start_file(
780 "foo",
781 FileOptions::default().compression_method(zip::CompressionMethod::Stored),
782 )
783 .unwrap();
784 zip.write_all(&data).unwrap();
785 },
786 |root| {
787 let data = vec![10; 2 << 20];
788 check_file(root, "foo", &data);
789 },
790 );
791 }
792
Jiyong Parke6587ca2021-05-17 14:42:23 +0900793 #[cfg(not(target_os = "android"))] // Android doesn't have the loopdev crate
794 #[test]
795 fn supports_zip_on_block_device() {
796 // Write test.zip to the test directory
797 let test_dir = tempfile::TempDir::new().unwrap();
798 let zip_path = test_dir.path().join("test.zip");
799 let mut zip_file = File::create(&zip_path).unwrap();
800 let data = include_bytes!("../testdata/test.zip");
801 zip_file.write_all(data).unwrap();
802
803 // Pad 0 to test.zip so that its size is multiple of 4096.
804 const BLOCK_SIZE: usize = 4096;
805 let size = (data.len() + BLOCK_SIZE) & !BLOCK_SIZE;
806 let pad_size = size - data.len();
807 assert!(pad_size != 0);
808 let pad = vec![0; pad_size];
809 zip_file.write_all(pad.as_slice()).unwrap();
810 drop(zip_file);
811
812 // Attach test.zip to a loop device
813 let lc = loopdev::LoopControl::open().unwrap();
814 let ld = scopeguard::guard(lc.next_free().unwrap(), |ld| {
815 ld.detach().unwrap();
816 });
817 ld.attach_file(&zip_path).unwrap();
818
819 // Start zipfuse over to the loop device (not the zip file)
820 run_fuse_and_check_test_zip(&test_dir.path(), &ld.path().unwrap());
821 }
Jiyong Park331d1ea2021-05-10 11:01:23 +0900822}