summaryrefslogtreecommitdiffstats
path: root/src/util/tar.rs
blob: 07ad79536fee23dc5b293365556ad59c96f51f6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::{
	ffi::CString,
	fs::DirBuilder,
	io::{self, Read},
	os::unix::ffi::OsStrExt,
	path::Path,
};

pub fn unpack<R: Read, P: AsRef<Path>>(archive: R, dest: P) -> io::Result<()> {
	let dest_path = dest.as_ref();

	DirBuilder::new().recursive(true).create(dest_path)?;

	let mut ar = tar::Archive::new(archive);
	ar.set_preserve_permissions(true);
	ar.set_preserve_mtime(true);
	ar.set_unpack_xattrs(true);

	for entry_r in ar.entries()? {
		let mut entry = entry_r?;
		if entry.unpack_in(dest_path)? {
			let header = entry.header();
			let uid = header.uid()? as libc::uid_t;
			let gid = header.gid()? as libc::gid_t;

			let path = CString::new(dest_path.join(entry.path()?).as_os_str().as_bytes())
				.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
			if unsafe { libc::lchown(path.as_ptr(), uid, gid) } < 0 {
				return Err(io::Error::last_os_error());
			}
		}
	}

	Ok(())
}