M1 primary view: wx-rs patched+extended (Linux/GTK3 build, widget bridge), vendored wx 3.3.3 + asic-rs in thirdparty/, UI-SPEC table+KPIs+dialogs, build scripts
This commit is contained in:
Vendored
+633
@@ -0,0 +1,633 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::cmp;
|
||||
use std::convert::TryFrom;
|
||||
use std::fs;
|
||||
use std::io::prelude::*;
|
||||
use std::io::{self, SeekFrom};
|
||||
use std::marker;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::entry::{EntryFields, EntryIo};
|
||||
use crate::error::TarError;
|
||||
use crate::header::BLOCK_SIZE;
|
||||
use crate::other;
|
||||
use crate::pax::*;
|
||||
use crate::{Entry, GnuExtSparseHeader, GnuSparseHeader, Header};
|
||||
|
||||
/// A top-level representation of an archive file.
|
||||
///
|
||||
/// This archive can have an entry added to it and it can be iterated over.
|
||||
pub struct Archive<R: ?Sized + Read> {
|
||||
inner: ArchiveInner<R>,
|
||||
}
|
||||
|
||||
pub struct ArchiveInner<R: ?Sized> {
|
||||
pos: Cell<u64>,
|
||||
mask: u32,
|
||||
unpack_xattrs: bool,
|
||||
preserve_permissions: bool,
|
||||
preserve_ownerships: bool,
|
||||
preserve_mtime: bool,
|
||||
overwrite: bool,
|
||||
ignore_zeros: bool,
|
||||
obj: RefCell<R>,
|
||||
}
|
||||
|
||||
/// An iterator over the entries of an archive.
|
||||
pub struct Entries<'a, R: 'a + Read> {
|
||||
fields: EntriesFields<'a>,
|
||||
_ignored: marker::PhantomData<&'a Archive<R>>,
|
||||
}
|
||||
|
||||
trait SeekRead: Read + Seek {}
|
||||
impl<R: Read + Seek> SeekRead for R {}
|
||||
|
||||
struct EntriesFields<'a> {
|
||||
archive: &'a Archive<dyn Read + 'a>,
|
||||
seekable_archive: Option<&'a Archive<dyn SeekRead + 'a>>,
|
||||
next: u64,
|
||||
done: bool,
|
||||
raw: bool,
|
||||
}
|
||||
|
||||
impl<R: Read> Archive<R> {
|
||||
/// Create a new archive with the underlying object as the reader.
|
||||
pub fn new(obj: R) -> Archive<R> {
|
||||
Archive {
|
||||
inner: ArchiveInner {
|
||||
mask: u32::MIN,
|
||||
unpack_xattrs: false,
|
||||
preserve_permissions: false,
|
||||
preserve_ownerships: false,
|
||||
preserve_mtime: true,
|
||||
overwrite: true,
|
||||
ignore_zeros: false,
|
||||
obj: RefCell::new(obj),
|
||||
pos: Cell::new(0),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Unwrap this archive, returning the underlying object.
|
||||
pub fn into_inner(self) -> R {
|
||||
self.inner.obj.into_inner()
|
||||
}
|
||||
|
||||
/// Construct an iterator over the entries in this archive.
|
||||
///
|
||||
/// Note that care must be taken to consider each entry within an archive in
|
||||
/// sequence. If entries are processed out of sequence (from what the
|
||||
/// iterator returns), then the contents read for each entry may be
|
||||
/// corrupted.
|
||||
pub fn entries(&mut self) -> io::Result<Entries<'_, R>> {
|
||||
let me: &mut Archive<dyn Read> = self;
|
||||
me._entries(None).map(|fields| Entries {
|
||||
fields,
|
||||
_ignored: marker::PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
/// Unpacks the contents tarball into the specified `dst`.
|
||||
///
|
||||
/// This function will iterate over the entire contents of this tarball,
|
||||
/// extracting each file in turn to the location specified by the entry's
|
||||
/// path name.
|
||||
///
|
||||
/// # Security
|
||||
///
|
||||
/// See the [crate-level security documentation][crate#security]. If `dst`
|
||||
/// does not exist, it is created. Unpacking into an existing directory
|
||||
/// merges content.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use std::fs::File;
|
||||
/// use tar::Archive;
|
||||
///
|
||||
/// let mut ar = Archive::new(File::open("foo.tar").unwrap());
|
||||
/// ar.unpack("foo").unwrap();
|
||||
/// ```
|
||||
pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<()> {
|
||||
let me: &mut Archive<dyn Read> = self;
|
||||
me._unpack(dst.as_ref())
|
||||
}
|
||||
|
||||
/// Set the mask of the permission bits when unpacking this entry.
|
||||
///
|
||||
/// The mask will be inverted when applying against a mode, similar to how
|
||||
/// `umask` works on Unix. In logical notation it looks like:
|
||||
///
|
||||
/// ```text
|
||||
/// new_mode = old_mode & (~mask)
|
||||
/// ```
|
||||
///
|
||||
/// The mask is 0 by default and is currently only implemented on Unix.
|
||||
pub fn set_mask(&mut self, mask: u32) {
|
||||
self.inner.mask = mask;
|
||||
}
|
||||
|
||||
/// Indicate whether extended file attributes (xattrs on Unix) are preserved
|
||||
/// when unpacking this archive.
|
||||
///
|
||||
/// This flag is disabled by default and is currently only implemented on
|
||||
/// Unix using xattr support. This may eventually be implemented for
|
||||
/// Windows, however, if other archive implementations are found which do
|
||||
/// this as well.
|
||||
pub fn set_unpack_xattrs(&mut self, unpack_xattrs: bool) {
|
||||
self.inner.unpack_xattrs = unpack_xattrs;
|
||||
}
|
||||
|
||||
/// Indicate whether extended permissions (like suid on Unix) are preserved
|
||||
/// when unpacking this entry.
|
||||
///
|
||||
/// This flag is disabled by default and is currently only implemented on
|
||||
/// Unix.
|
||||
pub fn set_preserve_permissions(&mut self, preserve: bool) {
|
||||
self.inner.preserve_permissions = preserve;
|
||||
}
|
||||
|
||||
/// Indicate whether numeric ownership ids (like uid and gid on Unix)
|
||||
/// are preserved when unpacking this entry.
|
||||
///
|
||||
/// This flag is disabled by default and is currently only implemented on
|
||||
/// Unix.
|
||||
pub fn set_preserve_ownerships(&mut self, preserve: bool) {
|
||||
self.inner.preserve_ownerships = preserve;
|
||||
}
|
||||
|
||||
/// Indicate whether files and symlinks should be overwritten on extraction.
|
||||
pub fn set_overwrite(&mut self, overwrite: bool) {
|
||||
self.inner.overwrite = overwrite;
|
||||
}
|
||||
|
||||
/// Indicate whether access time information is preserved when unpacking
|
||||
/// this entry.
|
||||
///
|
||||
/// This flag is enabled by default.
|
||||
pub fn set_preserve_mtime(&mut self, preserve: bool) {
|
||||
self.inner.preserve_mtime = preserve;
|
||||
}
|
||||
|
||||
/// Ignore zeroed headers, which would otherwise indicate to the archive that it has no more
|
||||
/// entries.
|
||||
///
|
||||
/// This can be used in case multiple tar archives have been concatenated together.
|
||||
pub fn set_ignore_zeros(&mut self, ignore_zeros: bool) {
|
||||
self.inner.ignore_zeros = ignore_zeros;
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Seek + Read> Archive<R> {
|
||||
/// Construct an iterator over the entries in this archive for a seekable
|
||||
/// reader. Seek will be used to efficiently skip over file contents.
|
||||
///
|
||||
/// Note that care must be taken to consider each entry within an archive in
|
||||
/// sequence. If entries are processed out of sequence (from what the
|
||||
/// iterator returns), then the contents read for each entry may be
|
||||
/// corrupted.
|
||||
pub fn entries_with_seek(&mut self) -> io::Result<Entries<'_, R>> {
|
||||
let me: &Archive<dyn Read> = self;
|
||||
let me_seekable: &Archive<dyn SeekRead> = self;
|
||||
me._entries(Some(me_seekable)).map(|fields| Entries {
|
||||
fields,
|
||||
_ignored: marker::PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Archive<dyn Read + '_> {
|
||||
fn _entries<'a>(
|
||||
&'a self,
|
||||
seekable_archive: Option<&'a Archive<dyn SeekRead + 'a>>,
|
||||
) -> io::Result<EntriesFields<'a>> {
|
||||
if self.inner.pos.get() != 0 {
|
||||
return Err(other(
|
||||
"cannot call entries unless archive is at \
|
||||
position 0",
|
||||
));
|
||||
}
|
||||
Ok(EntriesFields {
|
||||
archive: self,
|
||||
seekable_archive,
|
||||
done: false,
|
||||
next: 0,
|
||||
raw: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn _unpack(&mut self, dst: &Path) -> io::Result<()> {
|
||||
if dst.symlink_metadata().is_err() {
|
||||
fs::create_dir_all(dst)
|
||||
.map_err(|e| TarError::new(format!("failed to create `{}`", dst.display()), e))?;
|
||||
}
|
||||
|
||||
// Canonicalizing the dst directory will prepend the path with '\\?\'
|
||||
// on windows which will allow windows APIs to treat the path as an
|
||||
// extended-length path with a 32,767 character limit. Otherwise all
|
||||
// unpacked paths over 260 characters will fail on creation with a
|
||||
// NotFound exception.
|
||||
let dst = &dst.canonicalize().unwrap_or(dst.to_path_buf());
|
||||
|
||||
// Delay any directory entries until the end (they will be created if needed by
|
||||
// descendants), to ensure that directory permissions do not interfere with descendant
|
||||
// extraction.
|
||||
let mut directories = Vec::new();
|
||||
for entry in self._entries(None)? {
|
||||
let mut file = entry.map_err(|e| TarError::new("failed to iterate over archive", e))?;
|
||||
if file.header().entry_type() == crate::EntryType::Directory {
|
||||
directories.push(file);
|
||||
} else {
|
||||
file.unpack_in(dst)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply the directories.
|
||||
//
|
||||
// Note: the order of application is important to permissions. That is, we must traverse
|
||||
// the filesystem graph in topological ordering or else we risk not being able to create
|
||||
// child directories within those of more restrictive permissions. See [0] for details.
|
||||
//
|
||||
// [0]: <https://github.com/alexcrichton/tar-rs/issues/242>
|
||||
directories.sort_by(|a, b| b.path_bytes().cmp(&a.path_bytes()));
|
||||
for mut dir in directories {
|
||||
dir.unpack_in(dst)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, R: Read> Entries<'a, R> {
|
||||
/// Indicates whether this iterator will return raw entries or not.
|
||||
///
|
||||
/// If the raw list of entries is returned, then no preprocessing happens
|
||||
/// on account of this library, for example taking into account GNU long name
|
||||
/// or long link archive members. Raw iteration is disabled by default.
|
||||
pub fn raw(self, raw: bool) -> Entries<'a, R> {
|
||||
Entries {
|
||||
fields: EntriesFields { raw, ..self.fields },
|
||||
_ignored: marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'a, R: Read> Iterator for Entries<'a, R> {
|
||||
type Item = io::Result<Entry<'a, R>>;
|
||||
|
||||
fn next(&mut self) -> Option<io::Result<Entry<'a, R>>> {
|
||||
self.fields
|
||||
.next()
|
||||
.map(|result| result.map(|e| EntryFields::from(e).into_entry()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> EntriesFields<'a> {
|
||||
fn next_entry_raw(
|
||||
&mut self,
|
||||
pax_extensions: Option<&[u8]>,
|
||||
) -> io::Result<Option<Entry<'a, io::Empty>>> {
|
||||
let mut header = Header::new_old();
|
||||
let mut header_pos = self.next;
|
||||
loop {
|
||||
// Seek to the start of the next header in the archive
|
||||
let delta = self.next - self.archive.inner.pos.get();
|
||||
self.skip(delta)?;
|
||||
|
||||
// EOF is an indicator that we are at the end of the archive.
|
||||
if !try_read_all(&mut &self.archive.inner, header.as_mut_bytes())? {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// If a header is not all zeros, we have another valid header.
|
||||
// Otherwise, check if we are ignoring zeros and continue, or break as if this is the
|
||||
// end of the archive.
|
||||
if !header.as_bytes().iter().all(|i| *i == 0) {
|
||||
self.next += BLOCK_SIZE;
|
||||
break;
|
||||
}
|
||||
|
||||
if !self.archive.inner.ignore_zeros {
|
||||
return Ok(None);
|
||||
}
|
||||
self.next += BLOCK_SIZE;
|
||||
header_pos = self.next;
|
||||
}
|
||||
|
||||
// Make sure the checksum is ok
|
||||
let sum = header.as_bytes()[..148]
|
||||
.iter()
|
||||
.chain(&header.as_bytes()[156..])
|
||||
.fold(0, |a, b| a + (*b as u32))
|
||||
+ 8 * 32;
|
||||
let cksum = header.cksum()?;
|
||||
if sum != cksum {
|
||||
return Err(other("archive header checksum mismatch"));
|
||||
}
|
||||
|
||||
// PAX extensions describe the *next file entry*, not intermediary
|
||||
// extension headers (GNU LongName `L`, GNU LongLink `K`, PAX `x`/`g`).
|
||||
let entry_type = header.entry_type();
|
||||
let is_extension_header = entry_type.is_gnu_longname()
|
||||
|| entry_type.is_gnu_longlink()
|
||||
|| entry_type.is_pax_local_extensions()
|
||||
|| entry_type.is_pax_global_extensions();
|
||||
|
||||
let mut pax_size: Option<u64> = None;
|
||||
if let Some(pax_extensions_ref) = pax_extensions.filter(|_| !is_extension_header) {
|
||||
pax_size = pax_extensions_value(pax_extensions_ref, PAX_SIZE);
|
||||
|
||||
if let Some(pax_uid) = pax_extensions_value(pax_extensions_ref, PAX_UID) {
|
||||
header.set_uid(pax_uid);
|
||||
}
|
||||
|
||||
if let Some(pax_gid) = pax_extensions_value(pax_extensions_ref, PAX_GID) {
|
||||
header.set_gid(pax_gid);
|
||||
}
|
||||
}
|
||||
|
||||
let file_pos = self.next;
|
||||
let mut size = header.entry_size()?;
|
||||
// If this exists, it must override the header size. Disagreement among
|
||||
// parsers allows construction of malicious archives that appear different
|
||||
// when parsed.
|
||||
if let Some(pax_size) = pax_size {
|
||||
size = pax_size;
|
||||
}
|
||||
let ret = EntryFields {
|
||||
size,
|
||||
header_pos,
|
||||
file_pos,
|
||||
data: vec![EntryIo::Data((&self.archive.inner).take(size))],
|
||||
header,
|
||||
long_pathname: None,
|
||||
long_linkname: None,
|
||||
pax_extensions: None,
|
||||
mask: self.archive.inner.mask,
|
||||
unpack_xattrs: self.archive.inner.unpack_xattrs,
|
||||
preserve_permissions: self.archive.inner.preserve_permissions,
|
||||
preserve_mtime: self.archive.inner.preserve_mtime,
|
||||
overwrite: self.archive.inner.overwrite,
|
||||
preserve_ownerships: self.archive.inner.preserve_ownerships,
|
||||
};
|
||||
|
||||
// Store where the next entry is, rounding up by 512 bytes (the size of
|
||||
// a header);
|
||||
let size = size
|
||||
.checked_add(BLOCK_SIZE - 1)
|
||||
.ok_or_else(|| other("size overflow"))?;
|
||||
self.next = self
|
||||
.next
|
||||
.checked_add(size & !(BLOCK_SIZE - 1))
|
||||
.ok_or_else(|| other("size overflow"))?;
|
||||
|
||||
Ok(Some(ret.into_entry()))
|
||||
}
|
||||
|
||||
fn next_entry(&mut self) -> io::Result<Option<Entry<'a, io::Empty>>> {
|
||||
if self.raw {
|
||||
return self.next_entry_raw(None);
|
||||
}
|
||||
|
||||
let mut gnu_longname = None;
|
||||
let mut gnu_longlink = None;
|
||||
let mut pax_extensions = None;
|
||||
let mut processed = 0;
|
||||
loop {
|
||||
processed += 1;
|
||||
let entry = match self.next_entry_raw(pax_extensions.as_deref())? {
|
||||
Some(entry) => entry,
|
||||
None if processed > 1 => {
|
||||
return Err(other(
|
||||
"members found describing a future member \
|
||||
but no future member found",
|
||||
));
|
||||
}
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let is_recognized_header =
|
||||
entry.header().as_gnu().is_some() || entry.header().as_ustar().is_some();
|
||||
|
||||
if is_recognized_header && entry.header().entry_type().is_gnu_longname() {
|
||||
if gnu_longname.is_some() {
|
||||
return Err(other(
|
||||
"two long name entries describing \
|
||||
the same member",
|
||||
));
|
||||
}
|
||||
gnu_longname = Some(EntryFields::from(entry).read_all()?);
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_recognized_header && entry.header().entry_type().is_gnu_longlink() {
|
||||
if gnu_longlink.is_some() {
|
||||
return Err(other(
|
||||
"two long name entries describing \
|
||||
the same member",
|
||||
));
|
||||
}
|
||||
gnu_longlink = Some(EntryFields::from(entry).read_all()?);
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_recognized_header && entry.header().entry_type().is_pax_local_extensions() {
|
||||
if pax_extensions.is_some() {
|
||||
return Err(other(
|
||||
"two pax extensions entries describing \
|
||||
the same member",
|
||||
));
|
||||
}
|
||||
pax_extensions = Some(EntryFields::from(entry).read_all()?);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut fields = EntryFields::from(entry);
|
||||
fields.long_pathname = gnu_longname;
|
||||
fields.long_linkname = gnu_longlink;
|
||||
fields.pax_extensions = pax_extensions;
|
||||
self.parse_sparse_header(&mut fields)?;
|
||||
return Ok(Some(fields.into_entry()));
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_sparse_header(&mut self, entry: &mut EntryFields<'a>) -> io::Result<()> {
|
||||
if !entry.header.entry_type().is_gnu_sparse() {
|
||||
return Ok(());
|
||||
}
|
||||
let gnu = match entry.header.as_gnu() {
|
||||
Some(gnu) => gnu,
|
||||
None => return Err(other("sparse entry type listed but not GNU header")),
|
||||
};
|
||||
|
||||
// Sparse files are represented internally as a list of blocks that are
|
||||
// read. Blocks are either a bunch of 0's or they're data from the
|
||||
// underlying archive.
|
||||
//
|
||||
// Blocks of a sparse file are described by the `GnuSparseHeader`
|
||||
// structure, some of which are contained in `GnuHeader` but some of
|
||||
// which may also be contained after the first header in further
|
||||
// headers.
|
||||
//
|
||||
// We read off all the blocks here and use the `add_block` function to
|
||||
// incrementally add them to the list of I/O block (in `entry.data`).
|
||||
// The `add_block` function also validates that each chunk comes after
|
||||
// the previous, we don't overrun the end of the file, and each block is
|
||||
// aligned to a 512-byte boundary in the archive itself.
|
||||
//
|
||||
// At the end we verify that the sparse file size (`Header::size`) is
|
||||
// the same as the current offset (described by the list of blocks) as
|
||||
// well as the amount of data read equals the size of the entry
|
||||
// (`Header::entry_size`).
|
||||
entry.data.truncate(0);
|
||||
|
||||
let mut cur = 0;
|
||||
let mut remaining = entry.size;
|
||||
{
|
||||
let data = &mut entry.data;
|
||||
let reader = &self.archive.inner;
|
||||
let size = entry.size;
|
||||
let mut add_block = |block: &GnuSparseHeader| -> io::Result<_> {
|
||||
if block.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let off = block.offset()?;
|
||||
let len = block.length()?;
|
||||
if len != 0 && (size - remaining) % BLOCK_SIZE != 0 {
|
||||
return Err(other(
|
||||
"previous block in sparse file was not \
|
||||
aligned to 512-byte boundary",
|
||||
));
|
||||
} else if off < cur {
|
||||
return Err(other(
|
||||
"out of order or overlapping sparse \
|
||||
blocks",
|
||||
));
|
||||
} else if cur < off {
|
||||
let block = io::repeat(0).take(off - cur);
|
||||
data.push(EntryIo::Pad(block));
|
||||
}
|
||||
cur = off
|
||||
.checked_add(len)
|
||||
.ok_or_else(|| other("more bytes listed in sparse file than u64 can hold"))?;
|
||||
remaining = remaining.checked_sub(len).ok_or_else(|| {
|
||||
other(
|
||||
"sparse file consumed more data than the header \
|
||||
listed",
|
||||
)
|
||||
})?;
|
||||
data.push(EntryIo::Data(reader.take(len)));
|
||||
Ok(())
|
||||
};
|
||||
for block in gnu.sparse.iter() {
|
||||
add_block(block)?
|
||||
}
|
||||
if gnu.is_extended() {
|
||||
let mut ext = GnuExtSparseHeader::new();
|
||||
ext.isextended[0] = 1;
|
||||
while ext.is_extended() {
|
||||
if !try_read_all(&mut &self.archive.inner, ext.as_mut_bytes())? {
|
||||
return Err(other("failed to read extension"));
|
||||
}
|
||||
|
||||
self.next += BLOCK_SIZE;
|
||||
for block in ext.sparse.iter() {
|
||||
add_block(block)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if cur != gnu.real_size()? {
|
||||
return Err(other(
|
||||
"mismatch in sparse file chunks and \
|
||||
size in header",
|
||||
));
|
||||
}
|
||||
entry.size = cur;
|
||||
if remaining > 0 {
|
||||
return Err(other(
|
||||
"mismatch in sparse file chunks and \
|
||||
entry size in header",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn skip(&mut self, mut amt: u64) -> io::Result<()> {
|
||||
if let Some(seekable_archive) = self.seekable_archive {
|
||||
let pos = io::SeekFrom::Current(
|
||||
i64::try_from(amt).map_err(|_| other("seek position out of bounds"))?,
|
||||
);
|
||||
(&seekable_archive.inner).seek(pos)?;
|
||||
} else {
|
||||
let mut buf = [0u8; 4096 * 8];
|
||||
while amt > 0 {
|
||||
let n = cmp::min(amt, buf.len() as u64);
|
||||
let n = (&self.archive.inner).read(&mut buf[..n as usize])?;
|
||||
if n == 0 {
|
||||
return Err(other("unexpected EOF during skip"));
|
||||
}
|
||||
amt -= n as u64;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for EntriesFields<'a> {
|
||||
type Item = io::Result<Entry<'a, io::Empty>>;
|
||||
|
||||
fn next(&mut self) -> Option<io::Result<Entry<'a, io::Empty>>> {
|
||||
if self.done {
|
||||
None
|
||||
} else {
|
||||
match self.next_entry() {
|
||||
Ok(Some(e)) => Some(Ok(e)),
|
||||
Ok(None) => {
|
||||
self.done = true;
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
self.done = true;
|
||||
Some(Err(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: ?Sized + Read> Read for &ArchiveInner<R> {
|
||||
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
|
||||
let i = self.obj.borrow_mut().read(into)?;
|
||||
self.pos.set(self.pos.get() + i as u64);
|
||||
Ok(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: ?Sized + Seek> Seek for &ArchiveInner<R> {
|
||||
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||
let pos = self.obj.borrow_mut().seek(pos)?;
|
||||
self.pos.set(pos);
|
||||
Ok(pos)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to fill the buffer from the reader.
|
||||
///
|
||||
/// If the reader reaches its end before filling the buffer at all, returns `false`.
|
||||
/// Otherwise returns `true`.
|
||||
fn try_read_all<R: Read>(r: &mut R, buf: &mut [u8]) -> io::Result<bool> {
|
||||
let mut read = 0;
|
||||
while read < buf.len() {
|
||||
match r.read(&mut buf[read..])? {
|
||||
0 => {
|
||||
if read == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
return Err(other("failed to read entire block"));
|
||||
}
|
||||
n => read += n,
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Vendored
+1447
File diff suppressed because it is too large
Load Diff
Vendored
+974
@@ -0,0 +1,974 @@
|
||||
use std::borrow::Cow;
|
||||
use std::cmp;
|
||||
use std::fs;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::prelude::*;
|
||||
use std::io::{self, Error, ErrorKind, SeekFrom};
|
||||
use std::marker;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use filetime::{self, FileTime};
|
||||
|
||||
use crate::archive::ArchiveInner;
|
||||
use crate::error::TarError;
|
||||
use crate::header::bytes2path;
|
||||
use crate::other;
|
||||
use crate::{Archive, Header, PaxExtensions};
|
||||
|
||||
/// A read-only view into an entry of an archive.
|
||||
///
|
||||
/// This structure is a window into a portion of a borrowed archive which can
|
||||
/// be inspected. It acts as a file handle by implementing the Reader trait. An
|
||||
/// entry cannot be rewritten once inserted into an archive.
|
||||
pub struct Entry<'a, R: 'a + Read> {
|
||||
fields: EntryFields<'a>,
|
||||
_ignored: marker::PhantomData<&'a Archive<R>>,
|
||||
}
|
||||
|
||||
// private implementation detail of `Entry`, but concrete (no type parameters)
|
||||
// and also all-public to be constructed from other modules.
|
||||
pub struct EntryFields<'a> {
|
||||
pub long_pathname: Option<Vec<u8>>,
|
||||
pub long_linkname: Option<Vec<u8>>,
|
||||
pub pax_extensions: Option<Vec<u8>>,
|
||||
pub mask: u32,
|
||||
pub header: Header,
|
||||
pub size: u64,
|
||||
pub header_pos: u64,
|
||||
pub file_pos: u64,
|
||||
pub data: Vec<EntryIo<'a>>,
|
||||
pub unpack_xattrs: bool,
|
||||
pub preserve_permissions: bool,
|
||||
pub preserve_ownerships: bool,
|
||||
pub preserve_mtime: bool,
|
||||
pub overwrite: bool,
|
||||
}
|
||||
|
||||
pub enum EntryIo<'a> {
|
||||
Pad(io::Take<io::Repeat>),
|
||||
Data(io::Take<&'a ArchiveInner<dyn Read + 'a>>),
|
||||
}
|
||||
|
||||
/// When unpacking items the unpacked thing is returned to allow custom
|
||||
/// additional handling by users. Today the File is returned, in future
|
||||
/// the enum may be extended with kinds for links, directories etc.
|
||||
#[derive(Debug)]
|
||||
pub enum Unpacked {
|
||||
/// A file was unpacked.
|
||||
File(std::fs::File),
|
||||
/// A directory, hardlink, symlink, or other node was unpacked.
|
||||
#[doc(hidden)]
|
||||
__Nonexhaustive,
|
||||
}
|
||||
|
||||
impl<'a, R: Read> Entry<'a, R> {
|
||||
/// Returns the path name for this entry.
|
||||
///
|
||||
/// This method may fail if the pathname is not valid Unicode and this is
|
||||
/// called on a Windows platform.
|
||||
///
|
||||
/// Note that this function will convert any `\` characters to directory
|
||||
/// separators, and it will not always return the same value as
|
||||
/// `self.header().path()` as some archive formats have support for longer
|
||||
/// path names described in separate entries.
|
||||
///
|
||||
/// It is recommended to use this method instead of inspecting the `header`
|
||||
/// directly to ensure that various archive formats are handled correctly.
|
||||
pub fn path(&self) -> io::Result<Cow<'_, Path>> {
|
||||
self.fields.path()
|
||||
}
|
||||
|
||||
/// Returns the raw bytes listed for this entry.
|
||||
///
|
||||
/// Note that this function will convert any `\` characters to directory
|
||||
/// separators, and it will not always return the same value as
|
||||
/// `self.header().path_bytes()` as some archive formats have support for
|
||||
/// longer path names described in separate entries.
|
||||
pub fn path_bytes(&self) -> Cow<'_, [u8]> {
|
||||
self.fields.path_bytes()
|
||||
}
|
||||
|
||||
/// Returns the link name for this entry, if any is found.
|
||||
///
|
||||
/// This method may fail if the pathname is not valid Unicode and this is
|
||||
/// called on a Windows platform. `Ok(None)` being returned, however,
|
||||
/// indicates that the link name was not present.
|
||||
///
|
||||
/// Note that this function will convert any `\` characters to directory
|
||||
/// separators, and it will not always return the same value as
|
||||
/// `self.header().link_name()` as some archive formats have support for
|
||||
/// longer path names described in separate entries.
|
||||
///
|
||||
/// It is recommended to use this method instead of inspecting the `header`
|
||||
/// directly to ensure that various archive formats are handled correctly.
|
||||
pub fn link_name(&self) -> io::Result<Option<Cow<'_, Path>>> {
|
||||
self.fields.link_name()
|
||||
}
|
||||
|
||||
/// Returns the link name for this entry, in bytes, if listed.
|
||||
///
|
||||
/// Note that this will not always return the same value as
|
||||
/// `self.header().link_name_bytes()` as some archive formats have support for
|
||||
/// longer path names described in separate entries.
|
||||
pub fn link_name_bytes(&self) -> Option<Cow<'_, [u8]>> {
|
||||
self.fields.link_name_bytes()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the pax extensions contained in this entry.
|
||||
///
|
||||
/// Pax extensions are a form of archive where extra metadata is stored in
|
||||
/// key/value pairs in entries before the entry they're intended to
|
||||
/// describe. For example this can be used to describe long file name or
|
||||
/// other metadata like atime/ctime/mtime in more precision.
|
||||
///
|
||||
/// The returned iterator will yield key/value pairs for each extension.
|
||||
///
|
||||
/// `None` will be returned if this entry does not indicate that it itself
|
||||
/// contains extensions, or if there were no previous extensions describing
|
||||
/// it.
|
||||
///
|
||||
/// Note that global pax extensions are intended to be applied to all
|
||||
/// archive entries.
|
||||
///
|
||||
/// Also note that this function will read the entire entry if the entry
|
||||
/// itself is a list of extensions.
|
||||
pub fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions<'_>>> {
|
||||
self.fields.pax_extensions()
|
||||
}
|
||||
|
||||
/// Returns access to the header of this entry in the archive.
|
||||
///
|
||||
/// This provides access to the metadata for this entry in the archive.
|
||||
pub fn header(&self) -> &Header {
|
||||
&self.fields.header
|
||||
}
|
||||
|
||||
/// Returns access to the size of this entry in the archive.
|
||||
///
|
||||
/// In the event the size is stored in a pax extension, that size value
|
||||
/// will be referenced. Otherwise, the entry size will be stored in the header.
|
||||
pub fn size(&self) -> u64 {
|
||||
self.fields.size
|
||||
}
|
||||
|
||||
/// Returns the starting position, in bytes, of the header of this entry in
|
||||
/// the archive.
|
||||
///
|
||||
/// The header is always a contiguous section of 512 bytes, so if the
|
||||
/// underlying reader implements `Seek`, then the slice from `header_pos` to
|
||||
/// `header_pos + 512` contains the raw header bytes.
|
||||
pub fn raw_header_position(&self) -> u64 {
|
||||
self.fields.header_pos
|
||||
}
|
||||
|
||||
/// Returns the starting position, in bytes, of the file of this entry in
|
||||
/// the archive.
|
||||
///
|
||||
/// If the file of this entry is continuous (e.g. not a sparse file), and
|
||||
/// if the underlying reader implements `Seek`, then the slice from
|
||||
/// `file_pos` to `file_pos + entry_size` contains the raw file bytes.
|
||||
pub fn raw_file_position(&self) -> u64 {
|
||||
self.fields.file_pos
|
||||
}
|
||||
|
||||
/// Writes this file to the specified location.
|
||||
///
|
||||
/// This function will write the entire contents of this file into the
|
||||
/// location specified by `dst`. Metadata will also be propagated to the
|
||||
/// path `dst`.
|
||||
///
|
||||
/// This function will create a file at the path `dst`, and it is required
|
||||
/// that the intermediate directories are created. Any existing file at the
|
||||
/// location `dst` will be overwritten.
|
||||
///
|
||||
/// > **Note**: This function does not have as many sanity checks as
|
||||
/// > [`Archive::unpack`] or [`Entry::unpack_in`], and does not prevent
|
||||
/// > writes outside `dst`. See the [crate-level security
|
||||
/// > documentation][crate#security]. If you're unpacking untrusted
|
||||
/// > archives, prefer [`Entry::unpack_in`] instead.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use std::fs::File;
|
||||
/// use tar::Archive;
|
||||
///
|
||||
/// let mut ar = Archive::new(File::open("foo.tar").unwrap());
|
||||
///
|
||||
/// for (i, file) in ar.entries().unwrap().enumerate() {
|
||||
/// let mut file = file.unwrap();
|
||||
/// file.unpack(format!("file-{}", i)).unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<Unpacked> {
|
||||
self.fields.unpack(None, dst.as_ref())
|
||||
}
|
||||
|
||||
/// Extracts this file under the specified path, avoiding security issues.
|
||||
///
|
||||
/// This function will write the entire contents of this file into the
|
||||
/// location obtained by appending the path of this file in the archive to
|
||||
/// `dst`, creating any intermediate directories if needed. Metadata will
|
||||
/// also be propagated to the path `dst`. Any existing file at the location
|
||||
/// `dst` will be overwritten.
|
||||
///
|
||||
/// # Security
|
||||
///
|
||||
/// See the [crate-level security documentation][crate#security].
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use std::fs::File;
|
||||
/// use tar::Archive;
|
||||
///
|
||||
/// let mut ar = Archive::new(File::open("foo.tar").unwrap());
|
||||
///
|
||||
/// for (i, file) in ar.entries().unwrap().enumerate() {
|
||||
/// let mut file = file.unwrap();
|
||||
/// file.unpack_in("target").unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
pub fn unpack_in<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<bool> {
|
||||
self.fields.unpack_in(dst.as_ref())
|
||||
}
|
||||
|
||||
/// Set the mask of the permission bits when unpacking this entry.
|
||||
///
|
||||
/// The mask will be inverted when applying against a mode, similar to how
|
||||
/// `umask` works on Unix. In logical notation it looks like:
|
||||
///
|
||||
/// ```text
|
||||
/// new_mode = old_mode & (~mask)
|
||||
/// ```
|
||||
///
|
||||
/// The mask is 0 by default and is currently only implemented on Unix.
|
||||
pub fn set_mask(&mut self, mask: u32) {
|
||||
self.fields.mask = mask;
|
||||
}
|
||||
|
||||
/// Indicate whether extended file attributes (xattrs on Unix) are preserved
|
||||
/// when unpacking this entry.
|
||||
///
|
||||
/// This flag is disabled by default and is currently only implemented on
|
||||
/// Unix using xattr support. This may eventually be implemented for
|
||||
/// Windows, however, if other archive implementations are found which do
|
||||
/// this as well.
|
||||
pub fn set_unpack_xattrs(&mut self, unpack_xattrs: bool) {
|
||||
self.fields.unpack_xattrs = unpack_xattrs;
|
||||
}
|
||||
|
||||
/// Indicate whether extended permissions (like suid on Unix) are preserved
|
||||
/// when unpacking this entry.
|
||||
///
|
||||
/// This flag is disabled by default and is currently only implemented on
|
||||
/// Unix.
|
||||
pub fn set_preserve_permissions(&mut self, preserve: bool) {
|
||||
self.fields.preserve_permissions = preserve;
|
||||
}
|
||||
|
||||
/// Indicate whether access time information is preserved when unpacking
|
||||
/// this entry.
|
||||
///
|
||||
/// This flag is enabled by default.
|
||||
pub fn set_preserve_mtime(&mut self, preserve: bool) {
|
||||
self.fields.preserve_mtime = preserve;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, R: Read> Read for Entry<'a, R> {
|
||||
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
|
||||
self.fields.read(into)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> EntryFields<'a> {
|
||||
pub fn from<R: Read>(entry: Entry<R>) -> EntryFields {
|
||||
entry.fields
|
||||
}
|
||||
|
||||
pub fn into_entry<R: Read>(self) -> Entry<'a, R> {
|
||||
Entry {
|
||||
fields: self,
|
||||
_ignored: marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_all(&mut self) -> io::Result<Vec<u8>> {
|
||||
// Preallocate some data but don't let ourselves get too crazy now.
|
||||
let cap = cmp::min(self.size, 128 * 1024);
|
||||
let mut v = Vec::with_capacity(cap as usize);
|
||||
self.read_to_end(&mut v).map(|_| v)
|
||||
}
|
||||
|
||||
fn path(&self) -> io::Result<Cow<'_, Path>> {
|
||||
bytes2path(self.path_bytes())
|
||||
}
|
||||
|
||||
fn path_bytes(&self) -> Cow<'_, [u8]> {
|
||||
match self.long_pathname {
|
||||
Some(ref bytes) => {
|
||||
if let Some(&0) = bytes.last() {
|
||||
Cow::Borrowed(&bytes[..bytes.len() - 1])
|
||||
} else {
|
||||
Cow::Borrowed(bytes)
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(ref pax) = self.pax_extensions {
|
||||
let pax = PaxExtensions::new(pax)
|
||||
.filter_map(|f| f.ok())
|
||||
.find(|f| f.key_bytes() == b"path")
|
||||
.map(|f| f.value_bytes());
|
||||
if let Some(field) = pax {
|
||||
return Cow::Borrowed(field);
|
||||
}
|
||||
}
|
||||
self.header.path_bytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the path in a "lossy" way, used for error reporting ONLY.
|
||||
fn path_lossy(&self) -> String {
|
||||
String::from_utf8_lossy(&self.path_bytes()).to_string()
|
||||
}
|
||||
|
||||
fn link_name(&self) -> io::Result<Option<Cow<'_, Path>>> {
|
||||
match self.link_name_bytes() {
|
||||
Some(bytes) => bytes2path(bytes).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn link_name_bytes(&self) -> Option<Cow<'_, [u8]>> {
|
||||
match self.long_linkname {
|
||||
Some(ref bytes) => {
|
||||
if let Some(&0) = bytes.last() {
|
||||
Some(Cow::Borrowed(&bytes[..bytes.len() - 1]))
|
||||
} else {
|
||||
Some(Cow::Borrowed(bytes))
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(ref pax) = self.pax_extensions {
|
||||
let pax = PaxExtensions::new(pax)
|
||||
.filter_map(|f| f.ok())
|
||||
.find(|f| f.key_bytes() == b"linkpath")
|
||||
.map(|f| f.value_bytes());
|
||||
if let Some(field) = pax {
|
||||
return Some(Cow::Borrowed(field));
|
||||
}
|
||||
}
|
||||
self.header.link_name_bytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions<'_>>> {
|
||||
if self.pax_extensions.is_none() {
|
||||
if !self.header.entry_type().is_pax_global_extensions()
|
||||
&& !self.header.entry_type().is_pax_local_extensions()
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
self.pax_extensions = Some(self.read_all()?);
|
||||
}
|
||||
Ok(Some(PaxExtensions::new(
|
||||
self.pax_extensions.as_ref().unwrap(),
|
||||
)))
|
||||
}
|
||||
|
||||
fn unpack_in(&mut self, dst: &Path) -> io::Result<bool> {
|
||||
// Notes regarding bsdtar 2.8.3 / libarchive 2.8.3:
|
||||
// * Leading '/'s are trimmed. For example, `///test` is treated as
|
||||
// `test`.
|
||||
// * If the filename contains '..', then the file is skipped when
|
||||
// extracting the tarball.
|
||||
// * '//' within a filename is effectively skipped. An error is
|
||||
// logged, but otherwise the effect is as if any two or more
|
||||
// adjacent '/'s within the filename were consolidated into one
|
||||
// '/'.
|
||||
//
|
||||
// Most of this is handled by the `path` module of the standard
|
||||
// library, but we specially handle a few cases here as well.
|
||||
|
||||
let mut file_dst = dst.to_path_buf();
|
||||
{
|
||||
let path = self.path().map_err(|e| {
|
||||
TarError::new(
|
||||
format!("invalid path in entry header: {}", self.path_lossy()),
|
||||
e,
|
||||
)
|
||||
})?;
|
||||
for part in path.components() {
|
||||
match part {
|
||||
// Leading '/' characters, root paths, and '.'
|
||||
// components are just ignored and treated as "empty
|
||||
// components"
|
||||
Component::Prefix(..) | Component::RootDir | Component::CurDir => continue,
|
||||
|
||||
// If any part of the filename is '..', then skip over
|
||||
// unpacking the file to prevent directory traversal
|
||||
// security issues. See, e.g.: CVE-2001-1267,
|
||||
// CVE-2002-0399, CVE-2005-1918, CVE-2007-4131
|
||||
Component::ParentDir => return Ok(false),
|
||||
|
||||
Component::Normal(part) => file_dst.push(part),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Skip cases where only slashes or '.' parts were seen, because
|
||||
// this is effectively an empty filename.
|
||||
if *dst == *file_dst {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
// Skip entries without a parent (i.e. outside of FS root)
|
||||
let parent = match file_dst.parent() {
|
||||
Some(p) => p,
|
||||
None => return Ok(false),
|
||||
};
|
||||
|
||||
self.ensure_dir_created(dst, parent)
|
||||
.map_err(|e| TarError::new(format!("failed to create `{}`", parent.display()), e))?;
|
||||
|
||||
let canon_target = self.validate_inside_dst(dst, parent)?;
|
||||
|
||||
self.unpack(Some(&canon_target), &file_dst)
|
||||
.map_err(|e| TarError::new(format!("failed to unpack `{}`", file_dst.display()), e))?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Unpack as destination directory `dst`.
|
||||
fn unpack_dir(&mut self, dst: &Path) -> io::Result<()> {
|
||||
// If the directory already exists just let it slide
|
||||
fs::create_dir(dst).or_else(|err| {
|
||||
if err.kind() == ErrorKind::AlreadyExists {
|
||||
let prev = fs::symlink_metadata(dst);
|
||||
if prev.map(|m| m.is_dir()).unwrap_or(false) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(Error::new(
|
||||
err.kind(),
|
||||
format!("{} when creating dir {}", err, dst.display()),
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns access to the header of this entry in the archive.
|
||||
fn unpack(&mut self, target_base: Option<&Path>, dst: &Path) -> io::Result<Unpacked> {
|
||||
fn set_perms_ownerships(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
header: &Header,
|
||||
mask: u32,
|
||||
perms: bool,
|
||||
ownerships: bool,
|
||||
) -> io::Result<()> {
|
||||
// ownerships need to be set first to avoid stripping SUID bits in the permissions ...
|
||||
if ownerships {
|
||||
set_ownerships(dst, &f, header.uid()?, header.gid()?)?;
|
||||
}
|
||||
// ... then set permissions, SUID bits set here is kept
|
||||
if let Ok(mode) = header.mode() {
|
||||
set_perms(dst, f, mode, mask, perms)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_mtime(header: &Header) -> Option<FileTime> {
|
||||
header.mtime().ok().map(|mtime| {
|
||||
// For some more information on this see the comments in
|
||||
// `Header::fill_platform_from`, but the general idea is that
|
||||
// we're trying to avoid 0-mtime files coming out of archives
|
||||
// since some tools don't ingest them well. Perhaps one day
|
||||
// when Cargo stops working with 0-mtime archives we can remove
|
||||
// this.
|
||||
let mtime = if mtime == 0 { 1 } else { mtime };
|
||||
FileTime::from_unix_time(mtime as i64, 0)
|
||||
})
|
||||
}
|
||||
|
||||
let kind = self.header.entry_type();
|
||||
|
||||
if kind.is_dir() {
|
||||
self.unpack_dir(dst)?;
|
||||
set_perms_ownerships(
|
||||
dst,
|
||||
None,
|
||||
&self.header,
|
||||
self.mask,
|
||||
self.preserve_permissions,
|
||||
self.preserve_ownerships,
|
||||
)?;
|
||||
return Ok(Unpacked::__Nonexhaustive);
|
||||
} else if kind.is_hard_link() || kind.is_symlink() {
|
||||
let src = match self.link_name()? {
|
||||
Some(name) => name,
|
||||
None => {
|
||||
return Err(other(&format!(
|
||||
"hard link listed for {} but no link name found",
|
||||
String::from_utf8_lossy(self.header.as_bytes())
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
if src.iter().count() == 0 {
|
||||
return Err(other(&format!(
|
||||
"symlink destination for {} is empty",
|
||||
String::from_utf8_lossy(self.header.as_bytes())
|
||||
)));
|
||||
}
|
||||
|
||||
if kind.is_hard_link() {
|
||||
let link_src = match target_base {
|
||||
// If we're unpacking within a directory then ensure that
|
||||
// the destination of this hard link is both present and
|
||||
// inside our own directory. This is needed because we want
|
||||
// to make sure to not overwrite anything outside the root.
|
||||
//
|
||||
// Note that this logic is only needed for hard links
|
||||
// currently. With symlinks the `validate_inside_dst` which
|
||||
// happens before this method as part of `unpack_in` will
|
||||
// use canonicalization to ensure this guarantee. For hard
|
||||
// links though they're canonicalized to their existing path
|
||||
// so we need to validate at this time.
|
||||
Some(p) => {
|
||||
let link_src = p.join(src);
|
||||
self.validate_inside_dst(p, &link_src)?;
|
||||
link_src
|
||||
}
|
||||
None => src.into_owned(),
|
||||
};
|
||||
fs::hard_link(&link_src, dst).map_err(|err| {
|
||||
Error::new(
|
||||
err.kind(),
|
||||
format!(
|
||||
"{} when hard linking {} to {}",
|
||||
err,
|
||||
link_src.display(),
|
||||
dst.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
} else {
|
||||
symlink(&src, dst)
|
||||
.or_else(|err_io| {
|
||||
if err_io.kind() == io::ErrorKind::AlreadyExists && self.overwrite {
|
||||
// remove dest and try once more
|
||||
std::fs::remove_file(dst).and_then(|()| symlink(&src, dst))
|
||||
} else {
|
||||
Err(err_io)
|
||||
}
|
||||
})
|
||||
.map_err(|err| {
|
||||
Error::new(
|
||||
err.kind(),
|
||||
format!(
|
||||
"{} when symlinking {} to {}",
|
||||
err,
|
||||
src.display(),
|
||||
dst.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
// While permissions on symlinks are meaningless on most systems, the ownership
|
||||
// of symlinks is important as it dictates the access control to the symlink
|
||||
// itself.
|
||||
if self.preserve_ownerships {
|
||||
set_ownerships(dst, &None, self.header.uid()?, self.header.gid()?)?;
|
||||
}
|
||||
if self.preserve_mtime {
|
||||
if let Some(mtime) = get_mtime(&self.header) {
|
||||
filetime::set_symlink_file_times(dst, mtime, mtime).map_err(|e| {
|
||||
TarError::new(format!("failed to set mtime for `{}`", dst.display()), e)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(Unpacked::__Nonexhaustive);
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[allow(unused_variables)]
|
||||
fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not implemented"))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
|
||||
::std::os::windows::fs::symlink_file(src, dst)
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
|
||||
::std::os::unix::fs::symlink(src, dst)
|
||||
}
|
||||
} else if kind.is_pax_global_extensions()
|
||||
|| kind.is_pax_local_extensions()
|
||||
|| kind.is_gnu_longname()
|
||||
|| kind.is_gnu_longlink()
|
||||
{
|
||||
return Ok(Unpacked::__Nonexhaustive);
|
||||
};
|
||||
|
||||
// Old BSD-tar compatibility.
|
||||
// Names that have a trailing slash should be treated as a directory.
|
||||
// Only applies to old headers.
|
||||
if self.header.as_ustar().is_none() && self.path_bytes().ends_with(b"/") {
|
||||
self.unpack_dir(dst)?;
|
||||
set_perms_ownerships(
|
||||
dst,
|
||||
None,
|
||||
&self.header,
|
||||
self.mask,
|
||||
self.preserve_permissions,
|
||||
self.preserve_ownerships,
|
||||
)?;
|
||||
return Ok(Unpacked::__Nonexhaustive);
|
||||
}
|
||||
|
||||
// Note the lack of `else` clause above. According to the FreeBSD
|
||||
// documentation:
|
||||
//
|
||||
// > A POSIX-compliant implementation must treat any unrecognized
|
||||
// > typeflag value as a regular file.
|
||||
//
|
||||
// As a result if we don't recognize the kind we just write out the file
|
||||
// as we would normally.
|
||||
|
||||
// Ensure we write a new file rather than overwriting in-place which
|
||||
// is attackable; if an existing file is found unlink it.
|
||||
fn open(dst: &Path) -> io::Result<std::fs::File> {
|
||||
OpenOptions::new().write(true).create_new(true).open(dst)
|
||||
}
|
||||
let mut f = (|| -> io::Result<std::fs::File> {
|
||||
let mut f = open(dst).or_else(|err| {
|
||||
if err.kind() != ErrorKind::AlreadyExists {
|
||||
Err(err)
|
||||
} else if self.overwrite {
|
||||
match fs::remove_file(dst) {
|
||||
Ok(()) => open(dst),
|
||||
Err(ref e) if e.kind() == io::ErrorKind::NotFound => open(dst),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
})?;
|
||||
for io in self.data.drain(..) {
|
||||
match io {
|
||||
EntryIo::Data(mut d) => {
|
||||
let expected = d.limit();
|
||||
if io::copy(&mut d, &mut f)? != expected {
|
||||
return Err(other("failed to write entire file"));
|
||||
}
|
||||
}
|
||||
EntryIo::Pad(d) => {
|
||||
// TODO: checked cast to i64
|
||||
let to = SeekFrom::Current(d.limit() as i64);
|
||||
let size = f.seek(to)?;
|
||||
f.set_len(size)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(f)
|
||||
})()
|
||||
.map_err(|e| {
|
||||
let header = self.header.path_bytes();
|
||||
TarError::new(
|
||||
format!(
|
||||
"failed to unpack `{}` into `{}`",
|
||||
String::from_utf8_lossy(&header),
|
||||
dst.display()
|
||||
),
|
||||
e,
|
||||
)
|
||||
})?;
|
||||
|
||||
if self.preserve_mtime {
|
||||
if let Some(mtime) = get_mtime(&self.header) {
|
||||
filetime::set_file_handle_times(&f, Some(mtime), Some(mtime)).map_err(|e| {
|
||||
TarError::new(format!("failed to set mtime for `{}`", dst.display()), e)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
set_perms_ownerships(
|
||||
dst,
|
||||
Some(&mut f),
|
||||
&self.header,
|
||||
self.mask,
|
||||
self.preserve_permissions,
|
||||
self.preserve_ownerships,
|
||||
)?;
|
||||
if self.unpack_xattrs {
|
||||
set_xattrs(self, dst)?;
|
||||
}
|
||||
return Ok(Unpacked::File(f));
|
||||
|
||||
fn set_ownerships(
|
||||
dst: &Path,
|
||||
f: &Option<&mut std::fs::File>,
|
||||
uid: u64,
|
||||
gid: u64,
|
||||
) -> Result<(), TarError> {
|
||||
_set_ownerships(dst, f, uid, gid).map_err(|e| {
|
||||
TarError::new(
|
||||
format!(
|
||||
"failed to set ownerships to uid={:?}, gid={:?} \
|
||||
for `{}`",
|
||||
uid,
|
||||
gid,
|
||||
dst.display()
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
fn _set_ownerships(
|
||||
dst: &Path,
|
||||
f: &Option<&mut std::fs::File>,
|
||||
uid: u64,
|
||||
gid: u64,
|
||||
) -> io::Result<()> {
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
let uid: libc::uid_t = uid.try_into().map_err(|_| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("UID {} is too large!", uid))
|
||||
})?;
|
||||
let gid: libc::gid_t = gid.try_into().map_err(|_| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("GID {} is too large!", gid))
|
||||
})?;
|
||||
match f {
|
||||
Some(f) => unsafe {
|
||||
let fd = f.as_raw_fd();
|
||||
if libc::fchown(fd, uid, gid) != 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
None => unsafe {
|
||||
let path = std::ffi::CString::new(dst.as_os_str().as_bytes()).map_err(|e| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("path contains null character: {:?}", e),
|
||||
)
|
||||
})?;
|
||||
if libc::lchown(path.as_ptr(), uid, gid) != 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Windows does not support posix numeric ownership IDs
|
||||
#[cfg(any(windows, target_arch = "wasm32"))]
|
||||
fn _set_ownerships(
|
||||
_: &Path,
|
||||
_: &Option<&mut std::fs::File>,
|
||||
_: u64,
|
||||
_: u64,
|
||||
) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_perms(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
mode: u32,
|
||||
mask: u32,
|
||||
preserve: bool,
|
||||
) -> Result<(), TarError> {
|
||||
_set_perms(dst, f, mode, mask, preserve).map_err(|e| {
|
||||
TarError::new(
|
||||
format!(
|
||||
"failed to set permissions to {:o} \
|
||||
for `{}`",
|
||||
mode,
|
||||
dst.display()
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
fn _set_perms(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
mode: u32,
|
||||
mask: u32,
|
||||
preserve: bool,
|
||||
) -> io::Result<()> {
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
let mode = if preserve { mode } else { mode & 0o777 };
|
||||
let mode = mode & !mask;
|
||||
let perm = fs::Permissions::from_mode(mode as _);
|
||||
match f {
|
||||
Some(f) => f.set_permissions(perm),
|
||||
None => fs::set_permissions(dst, perm),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn _set_perms(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
mode: u32,
|
||||
_mask: u32,
|
||||
_preserve: bool,
|
||||
) -> io::Result<()> {
|
||||
if mode & 0o200 == 0o200 {
|
||||
return Ok(());
|
||||
}
|
||||
match f {
|
||||
Some(f) => {
|
||||
let mut perm = f.metadata()?.permissions();
|
||||
perm.set_readonly(true);
|
||||
f.set_permissions(perm)
|
||||
}
|
||||
None => {
|
||||
let mut perm = fs::metadata(dst)?.permissions();
|
||||
perm.set_readonly(true);
|
||||
fs::set_permissions(dst, perm)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[allow(unused_variables)]
|
||||
fn _set_perms(
|
||||
dst: &Path,
|
||||
f: Option<&mut std::fs::File>,
|
||||
mode: u32,
|
||||
mask: u32,
|
||||
_preserve: bool,
|
||||
) -> io::Result<()> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not implemented"))
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_arch = "wasm32"), feature = "xattr"))]
|
||||
fn set_xattrs(me: &mut EntryFields, dst: &Path) -> io::Result<()> {
|
||||
use std::ffi::OsStr;
|
||||
use std::os::unix::prelude::*;
|
||||
|
||||
let exts = match me.pax_extensions() {
|
||||
Ok(Some(e)) => e,
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let exts = exts
|
||||
.filter_map(|e| e.ok())
|
||||
.filter_map(|e| {
|
||||
let key = e.key_bytes();
|
||||
let prefix = crate::pax::PAX_SCHILYXATTR.as_bytes();
|
||||
key.strip_prefix(prefix).map(|rest| (rest, e))
|
||||
})
|
||||
.map(|(key, e)| (OsStr::from_bytes(key), e.value_bytes()));
|
||||
|
||||
for (key, value) in exts {
|
||||
xattr::set(dst, key, value).map_err(|e| {
|
||||
TarError::new(
|
||||
format!(
|
||||
"failed to set extended \
|
||||
attributes to {}. \
|
||||
Xattrs: key={:?}, value={:?}.",
|
||||
dst.display(),
|
||||
key,
|
||||
String::from_utf8_lossy(value)
|
||||
),
|
||||
e,
|
||||
)
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
// Windows does not completely support posix xattrs
|
||||
// https://en.wikipedia.org/wiki/Extended_file_attributes#Windows_NT
|
||||
#[cfg(any(windows, not(feature = "xattr"), target_arch = "wasm32"))]
|
||||
fn set_xattrs(_: &mut EntryFields, _: &Path) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_dir_created(&self, dst: &Path, dir: &Path) -> io::Result<()> {
|
||||
let mut ancestor = dir;
|
||||
let mut dirs_to_create = Vec::new();
|
||||
while ancestor.symlink_metadata().is_err() {
|
||||
dirs_to_create.push(ancestor);
|
||||
if let Some(parent) = ancestor.parent() {
|
||||
ancestor = parent;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for ancestor in dirs_to_create.into_iter().rev() {
|
||||
if let Some(parent) = ancestor.parent() {
|
||||
self.validate_inside_dst(dst, parent)?;
|
||||
}
|
||||
fs::create_dir_all(ancestor)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_inside_dst(&self, dst: &Path, file_dst: &Path) -> io::Result<PathBuf> {
|
||||
// Abort if target (canonical) parent is outside of `dst`
|
||||
let canon_parent = file_dst.canonicalize().map_err(|err| {
|
||||
Error::new(
|
||||
err.kind(),
|
||||
format!("{} while canonicalizing {}", err, file_dst.display()),
|
||||
)
|
||||
})?;
|
||||
let canon_target = dst.canonicalize().map_err(|err| {
|
||||
Error::new(
|
||||
err.kind(),
|
||||
format!("{} while canonicalizing {}", err, dst.display()),
|
||||
)
|
||||
})?;
|
||||
if !canon_parent.starts_with(&canon_target) {
|
||||
let err = TarError::new(
|
||||
format!(
|
||||
"trying to unpack outside of destination path: {}",
|
||||
canon_target.display()
|
||||
),
|
||||
// TODO: use ErrorKind::InvalidInput here? (minor breaking change)
|
||||
Error::new(ErrorKind::Other, "Invalid argument"),
|
||||
);
|
||||
return Err(err.into());
|
||||
}
|
||||
Ok(canon_target)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Read for EntryFields<'a> {
|
||||
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
|
||||
loop {
|
||||
match self.data.get_mut(0).map(|io| io.read(into)) {
|
||||
Some(Ok(0)) => {
|
||||
self.data.remove(0);
|
||||
}
|
||||
Some(r) => return r,
|
||||
None => return Ok(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Read for EntryIo<'a> {
|
||||
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
|
||||
match *self {
|
||||
EntryIo::Pad(ref mut io) => io.read(into),
|
||||
EntryIo::Data(ref mut io) => io.read(into),
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+197
@@ -0,0 +1,197 @@
|
||||
// See https://en.wikipedia.org/wiki/Tar_%28computing%29#UStar_format
|
||||
/// Indicate the type of content described by a header.
|
||||
///
|
||||
/// This is returned by [`crate::Header::entry_type()`] and should be used to
|
||||
/// distinguish between types of content.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum EntryType {
|
||||
/// Regular file
|
||||
Regular,
|
||||
/// Hard link
|
||||
Link,
|
||||
/// Symbolic link
|
||||
Symlink,
|
||||
/// Character device
|
||||
Char,
|
||||
/// Block device
|
||||
Block,
|
||||
/// Directory
|
||||
Directory,
|
||||
/// Named pipe (fifo)
|
||||
Fifo,
|
||||
/// Implementation-defined 'high-performance' type, treated as regular file
|
||||
Continuous,
|
||||
/// GNU extension - long file name
|
||||
GNULongName,
|
||||
/// GNU extension - long link name (link target)
|
||||
GNULongLink,
|
||||
/// GNU extension - sparse file
|
||||
GNUSparse,
|
||||
/// Global extended header
|
||||
XGlobalHeader,
|
||||
/// Extended Header
|
||||
XHeader,
|
||||
/// Hints that destructuring should not be exhaustive.
|
||||
///
|
||||
/// This enum may grow additional variants, so this makes sure clients
|
||||
/// don't count on exhaustive matching. (Otherwise, adding a new variant
|
||||
/// could break existing code.)
|
||||
#[doc(hidden)]
|
||||
__Nonexhaustive(u8),
|
||||
}
|
||||
|
||||
impl EntryType {
|
||||
/// Creates a new entry type from a raw byte.
|
||||
///
|
||||
/// Note that the other named constructors of entry type may be more
|
||||
/// appropriate to create a file type from.
|
||||
pub fn new(byte: u8) -> EntryType {
|
||||
match byte {
|
||||
b'\x00' | b'0' => EntryType::Regular,
|
||||
b'1' => EntryType::Link,
|
||||
b'2' => EntryType::Symlink,
|
||||
b'3' => EntryType::Char,
|
||||
b'4' => EntryType::Block,
|
||||
b'5' => EntryType::Directory,
|
||||
b'6' => EntryType::Fifo,
|
||||
b'7' => EntryType::Continuous,
|
||||
b'x' => EntryType::XHeader,
|
||||
b'g' => EntryType::XGlobalHeader,
|
||||
b'L' => EntryType::GNULongName,
|
||||
b'K' => EntryType::GNULongLink,
|
||||
b'S' => EntryType::GNUSparse,
|
||||
b => EntryType::__Nonexhaustive(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the raw underlying byte that this entry type represents.
|
||||
pub fn as_byte(&self) -> u8 {
|
||||
match *self {
|
||||
EntryType::Regular => b'0',
|
||||
EntryType::Link => b'1',
|
||||
EntryType::Symlink => b'2',
|
||||
EntryType::Char => b'3',
|
||||
EntryType::Block => b'4',
|
||||
EntryType::Directory => b'5',
|
||||
EntryType::Fifo => b'6',
|
||||
EntryType::Continuous => b'7',
|
||||
EntryType::XHeader => b'x',
|
||||
EntryType::XGlobalHeader => b'g',
|
||||
EntryType::GNULongName => b'L',
|
||||
EntryType::GNULongLink => b'K',
|
||||
EntryType::GNUSparse => b'S',
|
||||
EntryType::__Nonexhaustive(b) => b,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a regular file.
|
||||
pub fn file() -> EntryType {
|
||||
EntryType::Regular
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a hard link.
|
||||
pub fn hard_link() -> EntryType {
|
||||
EntryType::Link
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a symlink.
|
||||
pub fn symlink() -> EntryType {
|
||||
EntryType::Symlink
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a character special device.
|
||||
pub fn character_special() -> EntryType {
|
||||
EntryType::Char
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a block special device.
|
||||
pub fn block_special() -> EntryType {
|
||||
EntryType::Block
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a directory.
|
||||
pub fn dir() -> EntryType {
|
||||
EntryType::Directory
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a FIFO.
|
||||
pub fn fifo() -> EntryType {
|
||||
EntryType::Fifo
|
||||
}
|
||||
|
||||
/// Creates a new entry type representing a contiguous file.
|
||||
pub fn contiguous() -> EntryType {
|
||||
EntryType::Continuous
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a regular file.
|
||||
pub fn is_file(&self) -> bool {
|
||||
self == &EntryType::Regular
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a hard link.
|
||||
pub fn is_hard_link(&self) -> bool {
|
||||
self == &EntryType::Link
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a symlink.
|
||||
pub fn is_symlink(&self) -> bool {
|
||||
self == &EntryType::Symlink
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a character special device.
|
||||
pub fn is_character_special(&self) -> bool {
|
||||
self == &EntryType::Char
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a block special device.
|
||||
pub fn is_block_special(&self) -> bool {
|
||||
self == &EntryType::Block
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a directory.
|
||||
pub fn is_dir(&self) -> bool {
|
||||
self == &EntryType::Directory
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a FIFO.
|
||||
pub fn is_fifo(&self) -> bool {
|
||||
self == &EntryType::Fifo
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a contiguous file.
|
||||
pub fn is_contiguous(&self) -> bool {
|
||||
self == &EntryType::Continuous
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a GNU long name header.
|
||||
pub fn is_gnu_longname(&self) -> bool {
|
||||
self == &EntryType::GNULongName
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a GNU sparse header.
|
||||
pub fn is_gnu_sparse(&self) -> bool {
|
||||
self == &EntryType::GNUSparse
|
||||
}
|
||||
|
||||
/// Returns whether this type represents a GNU long link header.
|
||||
pub fn is_gnu_longlink(&self) -> bool {
|
||||
self == &EntryType::GNULongLink
|
||||
}
|
||||
|
||||
/// Returns whether this type represents PAX global extensions, that
|
||||
/// should affect all following entries. For more, see [PAX].
|
||||
///
|
||||
/// [PAX]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html
|
||||
pub fn is_pax_global_extensions(&self) -> bool {
|
||||
self == &EntryType::XGlobalHeader
|
||||
}
|
||||
|
||||
/// Returns whether this type represents PAX local extensions; these
|
||||
/// only affect the current entry. For more, see [PAX].
|
||||
///
|
||||
/// [PAX]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html
|
||||
pub fn is_pax_local_extensions(&self) -> bool {
|
||||
self == &EntryType::XHeader
|
||||
}
|
||||
}
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
use std::borrow::Cow;
|
||||
use std::error;
|
||||
use std::fmt;
|
||||
use std::io::{self, Error};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TarError {
|
||||
desc: Cow<'static, str>,
|
||||
io: io::Error,
|
||||
}
|
||||
|
||||
impl TarError {
|
||||
pub fn new(desc: impl Into<Cow<'static, str>>, err: Error) -> TarError {
|
||||
TarError {
|
||||
desc: desc.into(),
|
||||
io: err,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for TarError {
|
||||
fn description(&self) -> &str {
|
||||
&self.desc
|
||||
}
|
||||
|
||||
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
|
||||
Some(&self.io)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for TarError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.desc.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TarError> for Error {
|
||||
fn from(t: TarError) -> Error {
|
||||
Error::new(t.io.kind(), t)
|
||||
}
|
||||
}
|
||||
Vendored
+1766
File diff suppressed because it is too large
Load Diff
Vendored
+64
@@ -0,0 +1,64 @@
|
||||
//! A library for reading and writing TAR archives
|
||||
//!
|
||||
//! This library provides utilities necessary to manage [TAR archives][1]
|
||||
//! abstracted over a reader or writer. Great strides are taken to ensure that
|
||||
//! an archive is never required to be fully resident in memory, and all objects
|
||||
//! provide largely a streaming interface to read bytes from.
|
||||
//!
|
||||
//! [1]: https://en.wikipedia.org/wiki/Tar_%28computing%29
|
||||
//!
|
||||
//! # Security
|
||||
//!
|
||||
//! When unpacking archives ([`Archive::unpack`], [`Entry::unpack_in`]), a
|
||||
//! best-effort is made to prevent writing files outside the destination
|
||||
//! directory: paths containing `..` are rejected, and symlink targets within
|
||||
//! the archive are validated before use.
|
||||
//!
|
||||
//! **Concurrent mutation of the destination tree is outside the threat model.**
|
||||
//! If another process modifies the destination (for example, by atomically
|
||||
//! swapping a symlink) while extraction is in progress, this crate may follow
|
||||
//! a path outside the intended destination. Preventing such TOCTOU races
|
||||
//! requires OS primitives (e.g. `openat`/`O_PATH` used throughout) that this
|
||||
//! crate does not use. When extracting untrusted archives in an environment
|
||||
//! where the destination may be concurrently modified, use the [`cap-std`]
|
||||
//! crate and/or OS-level sandboxing.
|
||||
//!
|
||||
//! [`cap-std`]: https://docs.rs/cap-std/
|
||||
|
||||
// More docs about the detailed tar format can also be found here:
|
||||
// https://man.freebsd.org/cgi/man.cgi?query=tar&sektion=5&manpath=FreeBSD+8-current
|
||||
|
||||
// NB: some of the coding patterns and idioms here may seem a little strange.
|
||||
// This is currently attempting to expose a super generic interface while
|
||||
// also not forcing clients to codegen the entire crate each time they use
|
||||
// it. To that end lots of work is done to ensure that concrete
|
||||
// implementations are all found in this crate and the generic functions are
|
||||
// all just super thin wrappers (e.g. easy to codegen).
|
||||
|
||||
#![doc(html_root_url = "https://docs.rs/tar/0.4")]
|
||||
#![deny(missing_docs)]
|
||||
#![cfg_attr(test, deny(warnings))]
|
||||
|
||||
use std::io::{Error, ErrorKind};
|
||||
|
||||
pub use crate::archive::{Archive, Entries};
|
||||
pub use crate::builder::{Builder, EntryWriter};
|
||||
pub use crate::entry::{Entry, Unpacked};
|
||||
pub use crate::entry_type::EntryType;
|
||||
pub use crate::header::GnuExtSparseHeader;
|
||||
#[cfg(all(any(unix, windows), not(target_arch = "wasm32")))]
|
||||
pub use crate::header::DETERMINISTIC_TIMESTAMP;
|
||||
pub use crate::header::{GnuHeader, GnuSparseHeader, Header, HeaderMode, OldHeader, UstarHeader};
|
||||
pub use crate::pax::{PaxExtension, PaxExtensions};
|
||||
|
||||
mod archive;
|
||||
mod builder;
|
||||
mod entry;
|
||||
mod entry_type;
|
||||
mod error;
|
||||
mod header;
|
||||
mod pax;
|
||||
|
||||
fn other(msg: &str) -> Error {
|
||||
Error::new(ErrorKind::Other, msg)
|
||||
}
|
||||
Vendored
+195
@@ -0,0 +1,195 @@
|
||||
#![allow(dead_code)]
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::slice;
|
||||
use std::str;
|
||||
|
||||
use crate::other;
|
||||
|
||||
// Keywords for PAX extended header records.
|
||||
pub const PAX_NONE: &str = ""; // Indicates that no PAX key is suitable
|
||||
pub const PAX_PATH: &str = "path";
|
||||
pub const PAX_LINKPATH: &str = "linkpath";
|
||||
pub const PAX_SIZE: &str = "size";
|
||||
pub const PAX_UID: &str = "uid";
|
||||
pub const PAX_GID: &str = "gid";
|
||||
pub const PAX_UNAME: &str = "uname";
|
||||
pub const PAX_GNAME: &str = "gname";
|
||||
pub const PAX_MTIME: &str = "mtime";
|
||||
pub const PAX_ATIME: &str = "atime";
|
||||
pub const PAX_CTIME: &str = "ctime"; // Removed from later revision of PAX spec, but was valid
|
||||
pub const PAX_CHARSET: &str = "charset"; // Currently unused
|
||||
pub const PAX_COMMENT: &str = "comment"; // Currently unused
|
||||
|
||||
pub const PAX_SCHILYXATTR: &str = "SCHILY.xattr.";
|
||||
|
||||
// Keywords for GNU sparse files in a PAX extended header.
|
||||
pub const PAX_GNUSPARSE: &str = "GNU.sparse.";
|
||||
pub const PAX_GNUSPARSENUMBLOCKS: &str = "GNU.sparse.numblocks";
|
||||
pub const PAX_GNUSPARSEOFFSET: &str = "GNU.sparse.offset";
|
||||
pub const PAX_GNUSPARSENUMBYTES: &str = "GNU.sparse.numbytes";
|
||||
pub const PAX_GNUSPARSEMAP: &str = "GNU.sparse.map";
|
||||
pub const PAX_GNUSPARSENAME: &str = "GNU.sparse.name";
|
||||
pub const PAX_GNUSPARSEMAJOR: &str = "GNU.sparse.major";
|
||||
pub const PAX_GNUSPARSEMINOR: &str = "GNU.sparse.minor";
|
||||
pub const PAX_GNUSPARSESIZE: &str = "GNU.sparse.size";
|
||||
pub const PAX_GNUSPARSEREALSIZE: &str = "GNU.sparse.realsize";
|
||||
|
||||
/// An iterator over the pax extensions in an archive entry.
|
||||
///
|
||||
/// This iterator yields structures which can themselves be parsed into
|
||||
/// key/value pairs.
|
||||
pub struct PaxExtensions<'entry> {
|
||||
data: slice::Split<'entry, u8, fn(&u8) -> bool>,
|
||||
}
|
||||
|
||||
impl<'entry> PaxExtensions<'entry> {
|
||||
/// Create new pax extensions iterator from the given entry data.
|
||||
pub fn new(a: &'entry [u8]) -> Self {
|
||||
fn is_newline(a: &u8) -> bool {
|
||||
*a == b'\n'
|
||||
}
|
||||
PaxExtensions {
|
||||
data: a.split(is_newline),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A key/value pair corresponding to a pax extension.
|
||||
pub struct PaxExtension<'entry> {
|
||||
key: &'entry [u8],
|
||||
value: &'entry [u8],
|
||||
}
|
||||
|
||||
pub fn pax_extensions_value(a: &[u8], key: &str) -> Option<u64> {
|
||||
for extension in PaxExtensions::new(a) {
|
||||
let current_extension = match extension {
|
||||
Ok(ext) => ext,
|
||||
Err(_) => return None,
|
||||
};
|
||||
if current_extension.key() != Ok(key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let value = match current_extension.value() {
|
||||
Ok(value) => value,
|
||||
Err(_) => return None,
|
||||
};
|
||||
let result = match value.parse::<u64>() {
|
||||
Ok(result) => result,
|
||||
Err(_) => return None,
|
||||
};
|
||||
return Some(result);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl<'entry> Iterator for PaxExtensions<'entry> {
|
||||
type Item = io::Result<PaxExtension<'entry>>;
|
||||
|
||||
fn next(&mut self) -> Option<io::Result<PaxExtension<'entry>>> {
|
||||
let line = match self.data.next() {
|
||||
Some([]) => return None,
|
||||
Some(line) => line,
|
||||
None => return None,
|
||||
};
|
||||
|
||||
Some(
|
||||
line.iter()
|
||||
.position(|b| *b == b' ')
|
||||
.and_then(|i| {
|
||||
str::from_utf8(&line[..i])
|
||||
.ok()
|
||||
.and_then(|len| len.parse::<usize>().ok().map(|j| (i + 1, j)))
|
||||
})
|
||||
.and_then(|(kvstart, reported_len)| {
|
||||
if line.len() + 1 == reported_len {
|
||||
line[kvstart..]
|
||||
.iter()
|
||||
.position(|b| *b == b'=')
|
||||
.map(|equals| (kvstart, equals))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.map(|(kvstart, equals)| PaxExtension {
|
||||
key: &line[kvstart..kvstart + equals],
|
||||
value: &line[kvstart + equals + 1..],
|
||||
})
|
||||
.ok_or_else(|| other("malformed pax extension")),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'entry> PaxExtension<'entry> {
|
||||
/// Returns the key for this key/value pair parsed as a string.
|
||||
///
|
||||
/// May fail if the key isn't actually utf-8.
|
||||
pub fn key(&self) -> Result<&'entry str, str::Utf8Error> {
|
||||
str::from_utf8(self.key)
|
||||
}
|
||||
|
||||
/// Returns the underlying raw bytes for the key of this key/value pair.
|
||||
pub fn key_bytes(&self) -> &'entry [u8] {
|
||||
self.key
|
||||
}
|
||||
|
||||
/// Returns the value for this key/value pair parsed as a string.
|
||||
///
|
||||
/// May fail if the value isn't actually utf-8.
|
||||
pub fn value(&self) -> Result<&'entry str, str::Utf8Error> {
|
||||
str::from_utf8(self.value)
|
||||
}
|
||||
|
||||
/// Returns the underlying raw bytes for this value of this key/value pair.
|
||||
pub fn value_bytes(&self) -> &'entry [u8] {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension trait for `Builder` to append PAX extended headers.
|
||||
impl<T: Write> crate::Builder<T> {
|
||||
/// Append PAX extended headers to the archive.
|
||||
///
|
||||
/// Takes in an iterator over the list of headers to add to convert it into a header set formatted.
|
||||
///
|
||||
/// Returns io::Error if an error occurs, else it returns ()
|
||||
pub fn append_pax_extensions<'key, 'value>(
|
||||
&mut self,
|
||||
headers: impl IntoIterator<Item = (&'key str, &'value [u8])>,
|
||||
) -> Result<(), io::Error> {
|
||||
// Store the headers formatted before write
|
||||
let mut data: Vec<u8> = Vec::new();
|
||||
|
||||
// For each key in headers, convert into a sized space and add it to data.
|
||||
// This will then be written in the file
|
||||
for (key, value) in headers {
|
||||
let mut len_len = 1;
|
||||
let mut max_len = 10;
|
||||
let rest_len = 3 + key.len() + value.len();
|
||||
while rest_len + len_len >= max_len {
|
||||
len_len += 1;
|
||||
max_len *= 10;
|
||||
}
|
||||
let len = rest_len + len_len;
|
||||
write!(&mut data, "{} {}=", len, key)?;
|
||||
data.extend_from_slice(value);
|
||||
data.push(b'\n');
|
||||
}
|
||||
|
||||
// Ignore the header append if it's empty.
|
||||
if data.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Create a header of type XHeader, set the size to the length of the
|
||||
// data, set the entry type to XHeader, and set the checksum
|
||||
// then append the header and the data to the archive.
|
||||
let mut header = crate::Header::new_ustar();
|
||||
let data_as_bytes: &[u8] = &data;
|
||||
header.set_size(data_as_bytes.len() as u64);
|
||||
header.set_entry_type(crate::EntryType::XHeader);
|
||||
header.set_cksum();
|
||||
self.append(&header, data_as_bytes)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user