use std::cell::{RefCell, Cell};
use std::cmp;
use std::fs;
use std::io::prelude::*;
use std::io;
use std::marker;
use std::path::{Path, Component};
use entry::EntryFields;
use error::TarError;
use other;
use {Entry, Header};
pub struct Archive<R: ?Sized + Read> {
inner: ArchiveInner<R>,
}
pub struct ArchiveInner<R: ?Sized> {
pos: Cell<u64>,
obj: RefCell<::AlignHigher<R>>,
}
pub struct Entries<'a, R: 'a + Read> {
fields: EntriesFields<'a>,
_ignored: marker::PhantomData<&'a Archive<R>>,
}
struct EntriesFields<'a> {
archive: &'a Archive<Read + 'a>,
next: u64,
done: bool,
raw: bool,
}
impl<R: Read> Archive<R> {
pub fn new(obj: R) -> Archive<R> {
Archive {
inner: ArchiveInner {
obj: RefCell::new(::AlignHigher(0, obj)),
pos: Cell::new(0),
},
}
}
pub fn into_inner(self) -> R {
self.inner.obj.into_inner().1
}
pub fn entries(&mut self) -> io::Result<Entries<R>> {
let me: &mut Archive<Read> = self;
me._entries().map(|fields| {
Entries { fields: fields, _ignored: marker::PhantomData }
})
}
pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<()> {
let me: &mut Archive<Read> = self;
me._unpack(dst.as_ref())
}
}
impl<'a> Archive<Read + 'a> {
fn _entries(&mut self) -> io::Result<EntriesFields> {
if self.inner.pos.get() != 0 {
return Err(other("cannot call entries unless archive is at \
position 0"))
}
Ok(EntriesFields {
archive: self,
done: false,
next: 0,
raw: false,
})
}
fn _unpack(&mut self, dst: &Path) -> io::Result<()> {
'outer: for entry in try!(self._entries()) {
let mut file = try!(entry.map_err(|e| {
TarError::new("failed to iterate over archive", e)
}));
let mut file_dst = dst.to_path_buf();
{
let path = try!(file.path().map_err(|e| {
TarError::new("invalid path in entry header", e)
}));
for part in path.components() {
match part {
Component::Prefix(..) |
Component::RootDir |
Component::CurDir => continue,
Component::ParentDir => continue 'outer,
Component::Normal(part) => file_dst.push(part),
}
}
}
if *dst == *file_dst {
continue
}
if let Some(parent) = file_dst.parent() {
try!(fs::create_dir_all(&parent).map_err(|e| {
TarError::new(&format!("failed to create `{}`",
parent.display()), e)
}));
}
try!(file.unpack(&file_dst).map_err(|e| {
TarError::new(&format!("failed to unpack `{}`",
file_dst.display()), e)
}));
}
Ok(())
}
fn skip(&self, mut amt: u64) -> io::Result<()> {
let mut buf = [0u8; 4096 * 8];
while amt > 0 {
let n = cmp::min(amt, buf.len() as u64);
let n = try!((&self.inner).read(&mut buf[..n as usize]));
if n == 0 {
return Err(other("unexpected EOF during skip"))
}
amt -= n as u64;
}
Ok(())
}
}
impl<'a, R: Read> Entries<'a, R> {
pub fn raw(self, raw: bool) -> Entries<'a, R> {
Entries {
fields: EntriesFields {
raw: 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) -> io::Result<Option<Entry<'a, io::Empty>>> {
let delta = self.next - self.archive.inner.pos.get();
try!(self.archive.skip(delta));
let mut header = Header::new_old();
try!(read_all(&mut &self.archive.inner, header.as_mut_bytes()));
self.next += 512;
if header.as_bytes().iter().all(|i| *i == 0) {
try!(read_all(&mut &self.archive.inner,
header.as_mut_bytes()));
self.next += 512;
return if header.as_bytes().iter().all(|i| *i == 0) {
Ok(None)
} else {
Err(other("found block of 0s not followed by a second \
block of 0s"))
}
}
let sum = header.as_bytes()[..148].iter()
.chain(&header.as_bytes()[156..])
.fold(0, |a, b| a + (*b as u32)) + 8 * 32;
let cksum = try!(header.cksum());
if sum != cksum {
return Err(other("archive header checksum mismatch"))
}
let size = try!(header.size());
let ret = EntryFields {
size: size,
header: header,
data: (&self.archive.inner).take(size),
long_pathname: None,
long_linkname: None,
pax_extensions: None,
};
let size = (ret.size + 511) & !(512 - 1);
self.next += size;
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()
}
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 try!(self.next_entry_raw()) {
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),
};
if entry.header().as_gnu().is_some() &&
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(try!(EntryFields::from(entry).read_all()));
continue
}
if entry.header().as_gnu().is_some() &&
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(try!(EntryFields::from(entry).read_all()));
continue
}
if entry.header().as_ustar().is_some() &&
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(try!(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;
return Ok(Some(fields.into_entry()))
}
}
}
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<'a, R: ?Sized + Read> Read for &'a ArchiveInner<R> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
self.obj.borrow_mut().read(into).map(|i| {
self.pos.set(self.pos.get() + i as u64);
i
})
}
}
fn read_all<R: Read>(r: &mut R, buf: &mut [u8]) -> io::Result<()> {
let mut read = 0;
while read < buf.len() {
match try!(r.read(&mut buf[read..])) {
0 => return Err(other("failed to read entire block")),
n => read += n,
}
}
Ok(())
}