Tar archives
Tar puts many files and folders into one file; it is the usual way to pack a folder on Linux and macOS, and Docker images are made of tar files. This lesson creates, lists, reads and unpacks tar archives with System.Formats.Tar.
What you will learn#
- what a tar file is and how it differs from ZIP and GZip,
- making a tar file from a folder (
TarFile.CreateFromDirectory), - listing the entries with
TarReader, - reading one file without unpacking the rest,
- unpacking (
TarFile.ExtractToDirectory).
ZIP, GZip and tar#
| Format | What it does |
|---|---|
| ZIP (the tutorial Files and folders) | collects files and compresses each one |
| GZip (the tutorial Compression) | compresses one stream of data |
| tar | collects files and folders into one file, without compressing |
Linux programs combine the last two: a .tar.gz (or .tgz) file is a tar archive compressed with GZip. Tar also keeps things that ZIP does not always keep, such as Unix permissions and links.
The program#
# tar archives - make a .tar from a folder, list it, read one file from it and unpack it (System.Formats.Tar)
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Formats.Tar"
}
func main
oPath = new Path()
cBase = oPath.Combine([oPath.GetTempPath(),"ringdotnet_tar"])
cSource = oPath.Combine([cBase,"source"])
cTar = oPath.Combine([cBase,"backup.tar"])
cTarget = oPath.Combine([cBase,"unpacked"])
oDirectory = new Directory()
oFile = new File()
if oDirectory.Exists(cBase)
oDirectory.Delete([ :path = cBase, :recursive = True ])
ok
oDirectory.CreateDirectory(oPath.Combine([cSource,"notes"]))
oFile.WriteAllText([ :path = oPath.Combine([cSource,"readme.txt"]), :contents = "Read me first" ])
oFile.WriteAllText([ :path = oPath.Combine([cSource,"notes","a.txt"]), :contents = "Note A" ])
oFile.WriteAllText([ :path = oPath.Combine([cSource,"notes","b.txt"]), :contents = "Note B, a little longer" ])
# 1. Tar puts files and folders into ONE file (it does not compress: that is what gzip does, see the tutorial "Compression"). It is the usual
# format for packing a folder on Linux and macOS, and Docker images are tar files too.
new TarFile().CreateFromDirectory(cSource,cTar,False) # (source folder, tar file, include the folder itself)
? "1. the tar file exists: " + oFile.Exists(cTar) + ", size is a multiple of 512 bytes: " + (new FileInfo(cTar).Length % 512 = 0)
# 2. List what is inside: a TarReader gives the entries one after the other (GetNextEntry answers null at the end)
oStream = new FileStream(cTar,"Open")
oReader = new TarReader(oStream)
aLines = []
while true
oEntry = oReader.GetNextEntry(NULL)
if oEntry.isNull() exit ok
aLines + (padRight(oEntry.EntryType,16) + padRight(oEntry.Name,18) + oEntry.Length + " bytes")
end
? nl + "2. " + len(aLines) + " entries (sorted here, because the order in a tar file is the order of the folder):"
aSortedLines = sort(aLines)
for cLine in aSortedLines
? " " + cLine
next
oReader.Dispose()
oStream.Dispose()
# 3. Read one file from the archive without unpacking the others: look at each entry and read the data of the one we want
oStream = new FileStream(cTar,"Open")
oReader = new TarReader(oStream)
cFound = ""
while true
oEntry = oReader.GetNextEntry(NULL)
if oEntry.isNull() exit
but oEntry.Name = "notes/b.txt"
cFound = new StreamReader(oEntry.DataStream).ReadToEnd()
exit
ok
end
oReader.Dispose()
oStream.Dispose()
? nl + "3. text of notes/b.txt: " + cFound
# 4. Unpack everything into a folder (it must exist) and read a file from there
oDirectory.CreateDirectory(cTarget)
new TarFile().ExtractToDirectory(cTar,cTarget,True) # (tar file, target folder, overwrite files)
? nl + "4. unpacked: " + oFile.ReadAllText(oPath.Combine([cTarget,"readme.txt"])) + " / " + oFile.ReadAllText(oPath.Combine([cTarget,"notes","a.txt"]))
oDirectory.Delete([ :path = cBase, :recursive = True ])
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))1. the tar file exists: 1, size is a multiple of 512 bytes: 1
2. 4 entries (sorted here, because the order in a tar file is the order of the folder):
Directory notes/ 0 bytes
RegularFile notes/a.txt 6 bytes
RegularFile notes/b.txt 23 bytes
RegularFile readme.txt 13 bytes
3. text of notes/b.txt: Note B, a little longer
4. unpacked: Read me first / Note AHow it works#
Making the archive#
TarFile.CreateFromDirectory(source folder, tar file, include the folder itself) packs a whole folder. It is a static method of a static class, so the program calls it on new TarFile() with the arguments in order. Here the folder itself is not included, so the entries are readme.txt and notes/a.txt, not source/readme.txt. A tar file is built from blocks of 512 bytes, which step 1 checks: the size is a multiple of 512.
Reading the entries#
A TarReader is made on a stream (new TarReader(oStream)). GetNextEntry gives the next TarEntry, and null at the end, which isNull() tests. Each entry has Name, EntryType (RegularFile, Directory, SymbolicLink, ...) and Length. GetNextEntry has two forms, so it is called with NULL for the plain one. The entries come in the order of the folder, which depends on the file system, so the program sorts its lines before printing them: a test must not depend on the order of a disk.
One file from the archive#
Reading is sequential: a tar file has no index, so to find notes/b.txt the reader goes through the entries until it meets the name. DataStream of the entry is a stream with the content, read here with a StreamReader (the tutorial Streams and compression). The data is available only until you ask for the next entry. For a big archive this is both the strength of tar (it can be read as it arrives, from a network or a pipe) and its weakness (no quick access to the last file).
Unpacking#
TarFile.ExtractToDirectory(tar file, target folder, overwrite) writes all the entries to a folder, which must exist.
Never unpack an archive from an unknown source without checking the names of the entries. A bad archive can contain names such as ../../important.txt that try to write outside the target folder (the attack is called path traversal or zip slip). ExtractToDirectory refuses such names, but if you write your own loop with TarReader, check each Name with Path.GetFullPath first (the tutorial Paths and the environment).
What you learned#
- tar collects files without compressing them,
CreateFromDirectoryandExtractToDirectoryas static methods ofTarFile,TarReader,GetNextEntry,EntryType,DataStream,- reading is sequential,
- the danger of names that leave the target folder.
Exercises#
- Make a
.tar.gz: create the tar file, then compress it withGZipStream(the tutorial Compression). - Write
listTar(cFile)that returns the names of the entries as a Ring list. - Write a function that adds one more file to an archive with
TarWriter. - Make an archive with an empty folder and look at how it is listed.