silk.compress.tar.

Read and write tar archives as streams, one block of bytes at a time.

When to use#

Use a TarReader to unpack a .tar file, or a .tar.gz file as a silk.compress.inflate.Decoder decodes it. Give it the archive in pieces of any size with TarReader.step: it reports each member's header, then the member's content, and it never holds more than one header block. Use a TarWriter to write an archive to the ambient silk.io.writer.Writer: add members with TarWriter.file and TarWriter.directory, or send a large file in pieces with TarWriter.beginFile and TarWriter.writeContent, and end the archive with TarWriter.finish. For a .tar.gz, provide a silk.compress.deflate.EncodeWriter as the Writer. This module does not compress or decompress.

Details#

The reader understands ustar, GNU, and pax archives: the ustar prefix field, GNU long names and long link names, pax path, linkpath, and size records, and base-256 numbers. It does not allocate and does not keep a borrow of your input. Each header's checksum is checked. A member's path is checked before the member is reported: an absolute path, a backslash, a NUL, or a .. segment refuses the archive, so a caller that joins a path to a directory and creates no links never writes outside it. Empty and . segments are allowed, because tar -C dir . writes paths such as ./include/x.h.

The writer writes ustar headers with fixed metadata: modification time 0, owner and group 0 with no names, and mode 644, or 755 for an executable file or a directory. A path longer than 100 bytes goes in the ustar prefix field when it splits at a /, else in a pax path record. The same members in the same order give the same bytes on every host, so a checksum of the archive names its content.

Errors#

  • TarError from TarReader.step when a header is corrupt, the archive ends inside a member, a path is unsafe, or a long path does not fit the reader.

  • TarError from the writer when a path is one the reader would refuse, or when the members and their content come in the wrong order.

  • WriterError from the writer when the ambient Writer fails.

Examples#

Count the files of an archive given in small pieces#

silk
import silk.collections.slice {Slice}
import silk.compress.tar {TarError, TarKind, TarProgress, TarReader, TarStatus}
import silk.core.result {Result}

// Counts the regular files of `archive`, or answers -1 when it is not a valid tar archive. It
// gives the reader 100 bytes at a time, as a network or a decompressor would.
fn files(archive: &[u8]) -> i32 {
  let mut reader = TarReader.make()
  let mut count = 0
  let mut offset: usize = 0
  while true {
    let length = if archive.length - offset < 100 { archive.length - offset } else { 100 }
    let last = offset + length == archive.length
    let progress = match TarReader.step(&mut reader, Slice.view<u8>(archive, offset, length), last) {
      Result<TarProgress, TarError>.Success {value} => value
      Result<TarProgress, TarError>.Failure {..} => { return -1 }
    }
    offset = offset + progress.consumed
    if progress.status == TarStatus.Member && TarReader.member(&reader).kind == TarKind.File { count = count + 1 }
    if progress.status == TarStatus.End { return count }
  }
  return count
}

pub fn main() -> i32 {
  let empty: [u8; 1024] = [0; 1024]
  return files(&empty)
}

Write an archive and read it back#

silk
import silk.collections.slice {Slice}
import silk.compress.tar {TarError, TarProgress, TarReader, TarStatus, TarWriter}
import silk.core.effect {Effect}
import silk.core.result {Result}
import silk.io.writer {Writer, WriterError}

// A `Writer` that keeps up to 8 KiB in memory.
struct Memory {
  bytes: [u8; 8192],
  length: usize,
}

impl Writer for Memory {
  effect fn writeAll(self: &mut Self, value: &[u8]) -> () ! WriterError ? &mut Writer {
    if value.length > 8192 - self.length { fail Writer.failure() }
    Slice.copyInto<u8>(&mut self.bytes, self.length, value)
    self.length = self.length + value.length
  }

  effect fn flush(self: &mut Self) -> () ! WriterError ? &mut Writer { return () }
}

effect fn archive() -> () ! TarError | WriterError ? &mut Writer {
  let mut writer = TarWriter.make()
  run TarWriter.directory(&mut writer, b"app/bin")
  run TarWriter.file(&mut writer, b"app/bin/run", b"#!/bin/sh\n", true)
  // A file whose content arrives in pieces.
  run TarWriter.beginFile(&mut writer, b"app/README", 6, false)
  run TarWriter.writeContent(&mut writer, b"hel")
  run TarWriter.writeContent(&mut writer, b"lo\n")
  return run TarWriter.finish(move writer)
}

pub effect fn main() -> i32 ! TarError | WriterError {
  let mut memory = Memory {bytes: [0; 8192], length: 0}
  run archive() |> Effect.provideMut<Writer>(&mut memory)
  let mut reader = TarReader.make()
  let mut offset: usize = 0
  let mut members = 0
  while true {
    let input = Slice.view<u8>(&memory.bytes, offset, memory.length - offset)
    let progress = match TarReader.step(&mut reader, input, true) {
      Result<TarProgress, TarError>.Success {value} => value
      Result<TarProgress, TarError>.Failure {..} => { return 1 }
    }
    offset = offset + progress.consumed
    if progress.status == TarStatus.Member { members = members + 1 }
    if progress.status == TarStatus.End { break }
  }
  return if members == 3 { 0 } else { 2 }
}

Import as TarReader with import silk.compress.tar { TarReader }.

Public declarations: 8.

TarError#

silk
pub enum TarError

The reason a tar archive was refused, or a reader or writer was used out of order.

Truncated#

silk
Truncated

The archive ends inside a header or inside a member's content.

BadHeader#

silk
BadHeader

A header's checksum does not match its bytes, a number field holds something other than an octal or base-256 number, or a pax record is malformed.

UnsafePath#

silk
UnsafePath

A member path is absolute, holds a backslash or a NUL, or has a .. segment.

PathTooLong#

silk
PathTooLong

A GNU long name or long link name, or a pax path or linkpath record, is longer than PATH_LIMIT bytes.

InvalidUse#

silk
InvalidUse

A TarWriter call came in the wrong order: a new member or the end of the archive before the current file got all its content, or more content than the file's size. Or a TarReader was used after it failed.

Implementation TarError#

silk
impl TarError

Associated function describe#

silk
pub fn describe(error: TarError) -> string<'static>

Returns a short sentence that describes error, such as "the tar archive is truncated".

Implementation Debug for TarError#

silk
impl Debug for TarError

Operation debug#

silk
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut Writer

Writes the name of the variant, such as Truncated.

PATH_LIMIT#

silk
pub const PATH_LIMIT: usize

The longest path or link target, in bytes, that a GNU long-name header or a pax record can give a TarReader: 4096, the PATH_MAX of Linux.

TarKind#

silk
pub enum TarKind

What a tar member is.

File#

silk
File

A regular file. Its bytes come as Content progress after its Member progress.

Directory#

silk
Directory

A directory. Its name has no trailing /, and it has no content.

silk
SymbolicLink

A symbolic link to link, which the reader does not check.

silk
HardLink

A hard link to the earlier member link, which the reader does not check.

Other#

silk
Other

A device, a FIFO, or a type this module does not know.

TarMember#

silk
pub struct TarMember<'a>

The header of one member of a tar archive: its checked path, its kind, and its size.

Details#

The member's path is prefix/name, name alone when prefix is empty, or prefix alone when name is empty, as ustar writes a long directory path. A GNU long name or a pax path record comes back as name with an empty prefix. The slices borrow the TarReader, so copy what you keep before the next TarReader.step.

Field prefix#

silk
pub prefix: &'a [u8]

The ustar prefix field, or empty.

Field name#

silk
pub name: &'a [u8]

The rest of the path, without the trailing / a directory may carry.

Field kind#

silk
pub kind: TarKind

Whether the member is a file, a directory, a link, or something else.

Field executable#

silk
pub executable: bool

Whether the member is a file whose mode has an execute permission bit.

silk
pub link: &'a [u8]

The target of a symbolic or hard link, from a GNU long link name, a pax linkpath record, or the header's 100-byte link field. It is empty for other kinds.

Field size#

silk
pub size: u64

The number of content bytes of a regular file. It is zero for other kinds.

TarStatus#

silk
pub enum TarStatus

What a successful TarReader.step found.

NeedInput#

silk
NeedInput

All input is consumed and the archive goes on. Call again with more input.

Member#

silk
Member

A member's header is complete. Read it with TarReader.member before the next step. The content of a file follows as Content progress.

Content#

silk
Content

The first consumed bytes of the input are content of the current file, in order. Call TarReader.remaining to learn how many more follow.

End#

silk
End

The archive ended, at its end-of-archive block or at the end of the final input. Later steps return End and consume nothing.

TarProgress#

silk
pub struct TarProgress

The result of one successful TarReader.step.

Field consumed#

silk
pub consumed: usize

The number of input bytes that this call consumed, from the start of the input.

Field status#

silk
pub status: TarStatus

What the reader found.

Implementation Copy for TarProgress#

silk
impl Copy for TarProgress

TarReader#

silk
pub struct TarReader

A tar reader that takes the archive in pieces of any size.

When to use#

Make one with TarReader.make and call TarReader.step with the archive's bytes until it returns End. Each call consumes a prefix of its input, and the next call takes the input after that prefix. The archive can come from memory, a file, a socket, or a silk.compress.inflate.Decoder.

Details#

The reader does not allocate and does not borrow your input. It holds one 512-byte header and room for a long path and a long link target, PATH_LIMIT bytes each. Content is not copied: a Content progress names a prefix of the input that you gave. When you give the whole archive at once, each file's content comes back in one piece. The reader stops at the first all-zero block. After a failure, each step fails with InvalidUse.

Implementation TarReader#

silk
impl TarReader

Associated function make#

silk
pub fn make() -> TarReader

Returns a reader at the start of an archive.

Method step#

silk
pub fn step(self: &mut Self, input: &[u8], last: bool) -> Result<TarProgress, TarError>

Reads from the start of input and returns how much it consumed and what it found.

Details#

On the next call, give only the input after the consumed prefix, followed by any new bytes. The call returns at the first member header (Member), with the content of the current file (Content, always from the start of input), at the end of the archive (End), or when it consumed all of input (NeedInput). Set last when input holds the rest of the archive: then the archive may end without its end-of-archive blocks, at a member boundary or after a file's content without its final padding. GNU long-name and pax headers are read as part of the member they name, and pax global headers are skipped.

Errors#

  • TarError with Truncated when last is set and the archive ends inside a header or a member, BadHeader when a checksum, number, or pax record is invalid, UnsafePath when the member's path is absolute, holds a backslash or a NUL, or has a .. segment, and PathTooLong for a long path over PATH_LIMIT bytes. After a failure, each step fails with InvalidUse.

Method member#

silk
pub fn member<'a>(self: &'a Self) -> TarMember<'a>

Returns the header of the member that the last step reported with Member.

Details#

The member borrows the reader. It is valid until the next TarReader.step, which may overwrite the bytes it names. Before the first Member, it returns an empty member of kind Other.

Method remaining#

silk
pub fn remaining(self: &Self) -> u64

Returns the number of content bytes of the current file that no step has reported yet. It is zero between members, and after a file's last Content progress.

TarWriter#

silk
pub struct TarWriter

A tar archive being written to the ambient Writer, one member at a time.

When to use#

Make one with TarWriter.make, add members in the order the archive should list them, and end the archive with TarWriter.finish. Use TarWriter.file for a file whose content is in memory, and TarWriter.beginFile then TarWriter.writeContent for a file whose content comes in pieces.

Details#

The writer holds no buffer: each header, each piece of content, and each block's padding goes to the Writer as it comes. It writes ustar headers with fixed metadata: modification time zero, owner and group zero with empty names, and mode 644 for a file, 755 for an executable file or a directory. The same members in the same order therefore always give the same bytes, on any host. A path longer than the 100-byte name field is split into the ustar prefix and name at a / when it fits, and is otherwise written in a pax path record. A file of 8 GiB or more records its size in base-256. TarReader reads every archive the writer makes.

Gotchas#

The writer does not flush the Writer. Flush or finish the provider after TarWriter.finish.

Implementation TarWriter#

silk
impl TarWriter

Associated function make#

silk
pub fn make() -> TarWriter

Returns a writer with no members.

Method file#

silk
pub effect fn file(self: &mut Self, path: &[u8], content: &[u8], executable: bool) -> ()
    ! TarError | WriterError
    ? &mut Writer

Adds the regular file path holding content, with mode 755 when executable and 644 otherwise.

Errors#

  • TarError with UnsafePath when path is empty, absolute, ends in /, or holds a backslash, a NUL, or a .. segment, and InvalidUse when the last file begun with TarWriter.beginFile did not get all its content. Nothing is written.

  • WriterError when the Writer fails.

Method beginFile#

silk
pub effect fn beginFile(self: &mut Self, path: &[u8], size: u64, executable: bool) -> ()
    ! TarError | WriterError
    ? &mut Writer

Writes the header of the regular file path of size bytes, with mode 755 when executable and 644 otherwise. Send its content with TarWriter.writeContent.

Errors#

  • TarError with UnsafePath when path is empty, absolute, ends in /, or holds a backslash, a NUL, or a .. segment, and InvalidUse when the last file did not get all its content. Nothing is written.

  • WriterError when the Writer fails.

Method writeContent#

silk
pub effect fn writeContent(self: &mut Self, content: &[u8]) -> ()
    ! TarError | WriterError
    ? &mut Writer

Writes the next content bytes of the file that TarWriter.beginFile began, and the padding to a whole block after its last byte.

Errors#

  • TarError with InvalidUse when content is longer than the bytes the file still needs. Nothing is written.

  • WriterError when the Writer fails.

Method directory#

silk
pub effect fn directory(self: &mut Self, path: &[u8]) -> ()
    ! TarError | WriterError
    ? &mut Writer

Adds the directory path, with mode 755. Write it without a trailing /.

Errors#

  • TarError with UnsafePath when path is empty, absolute, ends in /, or holds a backslash, a NUL, or a .. segment, and InvalidUse when the last file did not get all its content. Nothing is written.

  • WriterError when the Writer fails.

Method finish#

silk
pub effect fn finish(self: TarWriter) -> ()
    ! TarError | WriterError
    ? &mut Writer

Ends the archive with its two zero blocks.

Errors#

  • TarError with InvalidUse when the last file did not get all its content. Nothing is written.

  • WriterError when the Writer fails.

Category: Data formats.

Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.

View the source of this page