-- | The entries of a tar archive, read as libarchive's tar reader reads-- them, the reader upstream's tarball fetcher unpacks with.---- The reader is a pure machine fed chunks, so an archive is read as it-- arrives: only a header, or the body of a header that names the next-- entry, is ever held whole, a pax body is read a record at a time, and a-- file's contents pass through as slices of the chunks fed. It reads the-- formats libarchive reads for source archives: v7, ustar with its prefix,-- GNU with its long names, and pax extended headers. A pax global header-- is read for the attributes libarchive refuses in one and applies to-- nothing, a GNU volume label is passed over, and a Solaris ACL header's-- body is skipped unparsed. A sparse member is refused, since nothing-- here rebuilds its holes.---- Names and link targets are bytes, as the archive carries them, and are-- copies, so an entry does not keep alive the chunk it was read from.module Nix.Fetch.Tar ( TarEntry (..), TarNode (..), TarFailure (..), TarStep (..), FileStep (..), tarReader, )whereimport Control.Applicative ((<|>))import Data.Bits (complement, shiftL, testBit, xor, (.&.), (.|.))import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport Data.Int (Int64, Int8)import Data.Maybe (fromMaybe, isNothing)import Data.Text (Text)import qualified Data.Text as Timport Data.Word (Word64, Word8)import Nix.Fetch.Url (bytesToTextLossy)-- ----------------------------------------------------------------------------- Entries and events-- ----------------------------------------------------------------------------- | One entry, once every header naming it is read.data TarEntry = TarEntry { -- | The path, as the archive names it. tarPath :: !ByteString, -- | The owner's execute bit of the entry's mode. tarExecutable :: !Bool, -- | What libarchive warns of while reading the entry's headers: the -- last warning, as its error string holds only the last. tarWarning :: !(Maybe Text) } deriving (Eq, Show)-- | An entry that is not a regular file.data TarNode = TarDirectory | TarSymlink !ByteString | -- | A hard link to the entry the path names. TarHardLink !ByteString | -- | A device or a FIFO, by the file type libarchive gives it. TarSpecial !Int deriving (Eq, Show)-- | Why an archive stopped reading, in libarchive's words.data TarFailure = -- | No format reader takes the input, so libarchive refuses to open it. TarUnrecognized | -- | A header, with the name the entry has so far, if it has one. TarHeaderFailure !(Maybe ByteString) !Text | -- | A regular file's contents. TarDataFailure !Text deriving (Eq, Show)-- | The reader between entries. Hand 'TarAwait' the next chunk, the-- empty chunk meaning the end of input. After 'TarDone' the rest of the-- input is not read, as libarchive reads nothing past the end-of-archive-- mark. The continuations of 'TarFile' and 'TarOther' are lazy, so an-- entry is handed over before the next is worked out.data TarStep = TarAwait !(ByteString -> TarStep) | -- | A regular file of the given size, whose contents follow. TarFile !TarEntry !Word64 FileStep | TarOther !TarEntry !TarNode TarStep | TarDone | TarFail !TarFailure-- | The reader inside a regular file's contents, which pass through as-- slices of the chunks fed.data FileStep = FileAwait !(ByteString -> FileStep) | FileChunk !ByteString FileStep | -- | The contents are complete, and the archive goes on. FileEnd TarStep | FileFail !TarFailure-- | The reader at the start of an archive.tarReader :: TarSteptarReader = headers FirstHeader FormatOld noPending BS.empty-- ----------------------------------------------------------------------------- Layout-- ----------------------------------------------------------------------------- | Every header is one block, and every body is padded to whole blocks.blockBytes :: IntblockBytes = 512-- | The bytes that pad a body of the given size to whole blocks.paddingOf :: Int64 -> Int64paddingOf size = negate size .&. fromIntegral (blockBytes - 1)-- | A header field, by its offset and width in the ustar layout.data Field = Field !Int !IntnameField, modeField, uidField, gidField, sizeField, mtimeField, checksumField, linkNameField, magicField, versionField, devMajorField, devMinorField, prefixField :: FieldnameField = Field 0 100modeField = Field 100 8uidField = Field 108 8gidField = Field 116 8sizeField = Field 124 12mtimeField = Field 136 12checksumField = Field 148 8linkNameField = Field 157 100magicField = Field 257 6versionField = Field 263 2devMajorField = Field 329 8devMinorField = Field 337 8prefixField = Field 345 155-- | Where the type flag is.typeFlagOffset :: InttypeFlagOffset = 156-- | The bytes of a field.fieldBytes :: Field -> ByteString -> ByteStringfieldBytes (Field offset width) = BS.take width . BS.drop offset-- | A string field, to its first NUL.fieldString :: Field -> ByteString -> ByteStringfieldString field = BS.takeWhile (/= 0) . fieldBytes field-- | A numeric field, as libarchive reads one.fieldNumber :: Field -> ByteString -> Int64fieldNumber field = tarNumber . fieldBytes field-- | The type flag of a header.typeFlag :: ByteString -> Word8typeFlag block = fromMaybe 0 (BS.indexMaybe block typeFlagOffset)-- | The magic and version a POSIX ustar header carries.ustarMagic, ustarVersion :: ByteStringustarMagic = "ustar\0"ustarVersion = "00"-- | The magic and version GNU tar writes, eight bytes together.gnuMagic, gnuVersion :: ByteStringgnuMagic = "ustar "gnuVersion = " \0"-- | Which writer a header's magic names, as libarchive tells them apart:-- GNU's whole eight bytes, then the five that POSIX's begins with.data Variant = VariantGnu | VariantUstar | VariantOldvariantOf :: ByteString -> VariantvariantOf block | hasGnuMagic block = VariantGnu | BS.take ustarStemBytes (fieldBytes magicField block) == BS.take ustarStemBytes ustarMagic = VariantUstar | otherwise = VariantOld where ustarStemBytes = 5hasGnuMagic, hasUstarMagic :: ByteString -> BoolhasGnuMagic block = fieldBytes magicField block == gnuMagic && fieldBytes versionField block == gnuVersionhasUstarMagic block = fieldBytes magicField block == ustarMagic && fieldBytes versionField block == ustarVersion-- | The path a header names: a ustar header's prefix and name joined by a-- slash unless the prefix ends in one, and otherwise the name. A GNU-- header holds times where ustar's prefix is, so it has none.headerPath :: ByteString -> ByteStringheaderPath block = case (variantOf block, BS.unsnoc prefix) of (VariantUstar, Just (_, lastByte)) | lastByte == slash -> prefix <> name | otherwise -> BS.snoc prefix slash <> name _ -> name where prefix = fieldString prefixField block name = fieldString nameField block-- ----------------------------------------------------------------------------- Numbers-- ----------------------------------------------------------------------------- | A numeric field as libarchive reads it: base 256 when its first byte-- has the high bit set, as GNU tar writes a value octal cannot hold, and-- otherwise octal.tarNumber :: ByteString -> Int64tarNumber bytes = case BS.uncons bytes of Just (lead, _) | testBit lead 7 -> base256 bytes _ -> baseN 8 bytes-- | A number in a base: leading spaces and tabs, an optional minus sign,-- then digits to the first byte that is not one, saturating on overflow.baseN :: Integer -> ByteString -> Int64baseN base bytes = go 0 digits where trimmed = BS.dropWhile (\b -> b == space || b == tab) bytes (sign, digits) = case BS.uncons trimmed of Just (b, rest) | b == minus -> (-1, rest) _ -> (1, trimmed) go :: Integer -> ByteString -> Int64 go !acc rest = case BS.uncons rest of Just (b, more) | b >= zero && toInteger (b - zero) < base -> step (acc * base + sign * toInteger (b - zero)) more _ -> fromInteger acc step next more | next > toInteger (maxBound :: Int64) = maxBound | next < toInteger (minBound :: Int64) = minBound | otherwise = go next more-- | A base-256 number: a big-endian two's complement value whose first byte's-- high bit is the base-256 marker, saturating where it overflows 64 bits.base256 :: ByteString -> Int64base256 bytes = case BS.uncons bytes of Nothing -> 0 Just (lead, rest) | testBit lead 6 -> fit 0xff (complement 0) (lead .|. 0x80) rest (BS.length bytes) | otherwise -> fit 0 0 (lead .&. 0x7f) rest (BS.length bytes) where fit :: Word8 -> Word64 -> Word8 -> ByteString -> Int -> Int64 fit signByte start c rest count | count > int64Bytes = case BS.uncons rest of Just (next, more) | c == signByte -> fit signByte start next more (count - 1) _ -> saturated signByte | (c `xor` signByte) .&. 0x80 /= 0 = saturated signByte | otherwise = fromIntegral (BS.foldl' shiftIn (shiftIn start c) rest) saturated signByte = if signByte == 0 then maxBound else minBound shiftIn acc b = shiftL acc 8 .|. fromIntegral b int64Bytes = 8-- ----------------------------------------------------------------------------- Header checks-- ----------------------------------------------------------------------------- | Whether a block is the end-of-archive mark, all zeros.nullBlock :: ByteString -> BoolnullBlock = BS.all (== 0)-- | libarchive's checksum test: the field holds octal, and equals the sum-- of the header's bytes with the field read as spaces, the bytes unsigned-- as POSIX says or signed as some old writers summed them.checksumValid :: ByteString -> BoolchecksumValid block = BS.all octalOrPadding stored && (expected == unsignedSum || expected == signedSum) where stored = fieldBytes checksumField block octalOrPadding c = c == space || c == 0 || (c >= zero && c <= seven) expected = toInteger (baseN 8 stored) Field offset width = checksumField outside = BS.take offset block <> BS.drop (offset + width) block fieldAsSpaces = toInteger width * toInteger space unsignedSum = fieldAsSpaces + BS.foldl' (\acc b -> acc + toInteger b) 0 outside signedSum = fieldAsSpaces + BS.foldl' (\acc b -> acc + toInteger (fromIntegral b :: Int8)) 0 outside-- | Whether libarchive's tar bidder takes a header: a valid checksum, a-- type flag that is NUL or alphanumeric, and number fields that are base-- 256 or octal with only padding after.bidsAsTar :: ByteString -> BoolbidsAsTar block = checksumValid block && (flag == 0 || isAlphaNumeric flag) && all (validNumber . (`fieldBytes` block)) [modeField, uidField, gidField, mtimeField, sizeField, devMajorField, devMinorField] where flag = typeFlag block isAlphaNumeric c = (c >= zero && c <= nine) || (c >= upperA && c <= upperZ) || (c >= lowerA && c <= lowerZ) validNumber bytes = case BS.uncons bytes of Just (marker, _) | marker == 0x80 || marker == 0xff || marker == 0 -> True _ -> BS.all (\c -> c == space || c == 0) (BS.dropWhile (\c -> c >= zero && c <= seven) (BS.dropWhile (== space) bytes))-- | Whether the bidder scores a header past 50, the threshold above which-- it takes a ustar header as the start of a tar archive and a hard link-- keeps no body: the header is taken, and carries POSIX's or GNU's magic.bidsAsHeader :: ByteString -> BoolbidsAsHeader block = bidsAsTar block && (hasUstarMagic block || hasGnuMagic block)-- ----------------------------------------------------------------------------- The header sequence-- ----------------------------------------------------------------------------- | Whether a header is the archive's first, where libarchive decides the-- input is a tar archive at all.data Position = FirstHeader | LaterHeader-- | The format libarchive records the archive as, as the last header-- sets it: it decides whether a hard link's size counts.data Format = FormatOld | FormatUstar | FormatGnu | FormatPax-- | What the headers before an entry's own have said about it.data Pending = Pending { pendingPath :: !(Maybe ByteString), pendingLink :: !(Maybe ByteString), pendingSize :: !(Maybe Int64), pendingSparse :: !Bool, pendingWarning :: !(Maybe Text), -- | The type flags of the headers seen. pendingSeen :: ![Word8], -- | Whether a header was seen after which the end of input is a -- damaged archive rather than its end: any but a volume label or a -- global header. pendingStarted :: !Bool }noPending :: PendingnoPending = Pending Nothing Nothing Nothing False Nothing [] False-- | Fail while reading an entry's headers, naming the entry as far as-- they have.failFor :: Pending -> Text -> TarStepfailFor pending = TarFail . TarHeaderFailure (pendingPath pending)-- | Read the headers of the next entry, from what is left of the last-- chunk.headers :: Position -> Format -> Pending -> ByteString -> TarStepheaders position format pending leftover = collect blockBytes leftover header short where short partial | BS.null partial && pendingStarted pending = failHeader "Damaged tar archive (end-of-archive within a sequence of headers)" | BS.null partial = TarDone | FirstHeader <- position = TarFail TarUnrecognized | otherwise = failHeader "Truncated tar archive detected while reading next header" header block rest | nullBlock block = TarDone | FirstHeader <- position, not (bidsAsTar block) = TarFail TarUnrecognized | not (checksumValid block) = failHeader "Damaged tar archive (bad header checksum)" | otherwise = special block rest failHeader = failFor pending later = headers LaterHeader seen flag = flag `elem` pendingSeen pending marked flag = pending { pendingSeen = flag : pendingSeen pending, pendingStarted = pendingStarted pending || (flag /= volumeFlag && flag /= globalFlag) } warned flag message | seen flag = (marked flag) {pendingWarning = Just message} | otherwise = marked flag metadataShort = failHeader "Truncated archive detected while reading metadata" special block rest = case typeFlag block of flag | flag == aclFlag, seen flag -> failHeader "Redundant 'A' header" | flag == aclFlag -> specialBody block rest (marked flag) (const id) (later FormatPax) | flag == globalFlag, seen flag -> failHeader "Redundant 'g' header" | flag == globalFlag -> paxHeader PaxGlobal block rest (marked flag) | flag == longLinkFlag -> specialBody block rest (warned flag "Damaged archive: Redundant 'K' headers may cause linknames to be incorrect") (\body updated -> updated {pendingLink = Just (cString body)}) (later FormatGnu) | flag == longNameFlag -> specialBody block rest (warned flag "Damaged archive: Redundant 'L' headers may cause filenames to be incorrect") (\body updated -> updated {pendingPath = Just (cString body)}) (later FormatGnu) | flag == volumeFlag, bodySize block < 0 || bodySize block > pathnameLimit -> failHeader "Damaged tar archive (invalid GNU volume header)" | flag == volumeFlag -> -- The label's block is consumed with its body, so a short input -- is reported against both. skipping (fromIntegral blockBytes + padded (bodySize block)) (fromIntegral blockBytes) rest (later FormatGnu (warned flag "Redundant 'V' header")) failHeader | flag == sunPaxFlag || flag == paxFlag, seen sunPaxFlag || seen paxFlag -> failHeader (if flag == paxFlag then "Redundant 'x' header" else "Redundant 'X'/'x' header") | flag == sunPaxFlag || flag == paxFlag -> paxHeader PaxExtended block rest (marked flag) | otherwise -> entryHeader format pending block rest -- The body of a long name, a long link or an ACL, held whole, with -- the headers' state once the flag is marked and how the body -- changes it. The body's padding is consumed with it, so a short -- input is reported against both. specialBody block rest marking update next | size < 0 || size > entryLimit = failHeader ("Special header has invalid size: " <> T.pack (show size)) | size > pathnameLimit = skipping (padded size) 0 rest (next marking {pendingWarning = Just ("Special header too large: " <> T.pack (show size) <> " > 1MiB")}) failHeader | otherwise = collect (fromIntegral size) rest (\body afterBody -> let updated = update body marking in skipping (size + paddingOf size) size afterBody (next updated) (failFor updated)) (const metadataShort) where size = bodySize block paxHeader scope block rest marking | size < 0 = failHeader ("pax extension header has invalid size: " <> T.pack (show size)) | size == 0 = failHeader (case scope of PaxGlobal -> "Invalid empty pax global extended header"; PaxExtended -> "Invalid empty pax extended header") | size > paxBodyLimit = skipping (padded size) 0 rest (later FormatPax marking {pendingWarning = Just ("Ignoring oversized pax extensions: " <> T.pack (show size) <> " > " <> T.pack (show paxBodyLimit))}) failHeader | otherwise = paxBody scope (later FormatPax) marking size rest where size = bodySize block-- | The size a special header's body declares.bodySize :: ByteString -> Int64bodySize = fieldNumber sizeField-- | A body's size with its padding.padded :: Int64 -> Int64padded size = size + paddingOf size-- | A string to its first NUL, as libarchive copies a header's body.cString :: ByteString -> ByteStringcString = BS.takeWhile (/= 0)-- | The longest body libarchive reads for a long name, a long link or a-- volume label: 1 MiB.pathnameLimit :: Int64pathnameLimit = 1048576-- | The largest pax body libarchive reads, 1 GiB, past which it passes-- over the body with a warning.paxBodyLimit :: Int64paxBodyLimit = 1073741824-- | The largest entry size libarchive accepts, 2^60 bytes.entryLimit :: Int64entryLimit = 0xfffffffffffffff-- ----------------------------------------------------------------------------- pax records-- ----------------------------------------------------------------------------- | What a pax header applies to: the entry after it, or, as a global-- header says, every entry after it, which libarchive does not do and so-- refuses the attributes that would need it.data PaxScope = PaxExtended | PaxGlobal-- | The names a pax body gives, which libarchive sets on the entry only-- once it has read the whole body.data PaxNames = PaxNames { paxPath :: !(Maybe ByteString), paxLink :: !(Maybe ByteString) }-- | The names set on the entry the body is for, a path or a link target-- of no bytes at all given having been ignored.applyNames :: PaxNames -> Pending -> PendingapplyNames names pending = pending { pendingPath = (cString <$> paxPath names) <|> pendingPath pending, pendingLink = (cString <$> paxLink names) <|> pendingLink pending }-- | What a pax key is for.data PaxKey = PathKey | LinkKey | SizeKey | SparseKey | OtherKeypaxKeyOf :: ByteString -> PaxKeypaxKeyOf key | key == "path" = PathKey | key == "linkpath" = LinkKey | key == "size" = SizeKey | "GNU.sparse." `BS.isPrefixOf` key = SparseKey | otherwise = OtherKey-- | One record of a pax body, read up to its value.data PaxRecord = PaxRecord { recordKey :: !ByteString, -- | The bytes of the record's length, key and equals sign. recordPrologue :: !Int, -- | The bytes of the record's value, its newline not counted. recordValue :: !Int64 }-- | Read a pax body a record at a time, as libarchive does, and keep only-- what it applies: the size, a sparse marker and the names, which are set-- once the body is read through. A malformed record warns and ends the-- reading, the rest of the body passed over, and the names before it are-- not set; a value is applied before its record's newline is checked. A-- global body applies nothing and refuses the attributes that libarchive-- would have to apply to every entry.---- @finish@ goes on from the headers once the body, with its padding, is-- read.paxBody :: PaxScope -> (Pending -> ByteString -> TarStep) -> Pending -> Int64 -> ByteString -> TarSteppaxBody scope finish marking size = records marking (PaxNames Nothing Nothing) size where padding = paddingOf size records pending names remaining bytes | remaining == 0 = let applied = applyNames names pending in skipping padding 0 bytes (finish applied) (failFor applied) | otherwise = peeking (fromIntegral (windowOf remaining)) bytes (record pending names remaining) (failFor pending "Truncated tar archive detected while reading pax attribute name") record pending names remaining ahead = case paxRecord (BS.take (fromIntegral (windowOf remaining)) ahead) remaining of Left message -> abandon pending message remaining ahead Right found | PaxGlobal <- scope, refusedGlobally (recordKey found) -> failFor pending ("Unsupported pax global extended header attribute '" <> bytesToTextLossy (recordKey found) <> "'") | otherwise -> value pending names (remaining - fromIntegral (recordPrologue found)) found (BS.drop (recordPrologue found) ahead) -- A record's value, from the bytes after its equals sign. value pending names remaining found bytes = case scope of PaxGlobal -> ignored pending PaxExtended -> case paxKeyOf (recordKey found) of PathKey -> keepName (\v -> names {paxPath = nonEmpty v}) LinkKey -> keepName (\v -> names {paxLink = nonEmpty v}) SizeKey -- A size too long to be a number fails without a message. | len > paxNumberLimit -> failFor pending "" | otherwise -> collect (fromIntegral len) bytes (sized . baseN 10) (const metadataShort) SparseKey -> ignored pending {pendingSparse = True} OtherKey -> ignored pending where len = recordValue found left = remaining - len nonEmpty v = if BS.null v then Nothing else Just v metadataShort = failFor pending "Truncated archive detected while reading metadata" ignored kept = skipping len 0 bytes (terminated kept names left) (const (failFor pending "Truncated tar archive detected while completing pax attribute")) -- A name too long to keep is passed over with a warning, and one -- of no bytes is not a name. keepName store | len > pathnameLimit = skipping len 0 bytes (terminated pending {pendingWarning = Just ""} names left) (failFor pending) | otherwise = collect (fromIntegral len) bytes (\v after -> terminated pending (store v) left after) (const metadataShort) sized number after | number < 0 || number == maxBound = failFor pending "Tar size attribute overflow" | otherwise = terminated pending {pendingSize = Just number} names left after -- A record ends in a newline, checked once its value is applied. terminated pending names remaining bytes = peeking 1 bytes check (failFor pending "Truncated tar archive detected while completing pax attribute") where check available = case BS.uncons available of Just (c, after) | c == lineFeed -> records pending names (remaining - 1) after _ -> abandon pending "Malformed pax attributes" remaining available -- A body that cannot be read on is passed over, with a warning. abandon pending message remaining bytes = skipping (remaining + padding) 0 bytes (finish pending {pendingWarning = Just message}) (failFor pending)-- | The most of a record libarchive looks at to find its length and key.paxPrologueBytes :: Int64paxPrologueBytes = 512-- | The bytes of what is left of a body that libarchive looks at to find-- the next record's length and key.windowOf :: Int64 -> Int64windowOf = min paxPrologueBytes-- | The longest record libarchive reads, as its length says.paxLineLimit :: Int64paxLineLimit = 99999999-- | The longest number a pax record may hold, as libarchive reads one.paxNumberLimit :: Int64paxNumberLimit = 64-- | The first record of what is left of a pax body, from the window-- libarchive looks at, or why it is malformed.paxRecord :: ByteString -> Int64 -> Either Text PaxRecordpaxRecord window remaining = do (lineLength, lengthBytes) <- paxLength window if lineLength > remaining then Left ("Ignoring malformed pax attribute: " <> T.pack (show lineLength) <> " > " <> T.pack (show remaining)) else Right () let keyArea = BS.take (fromIntegral lineLength - lengthBytes) (BS.drop lengthBytes window) case BS.uncons keyArea of Just (c, _) | c /= equals -> Right () _ -> Left "Ignoring malformed pax attributes: empty name found" keyLength <- maybe (Left "Ignoring malformed pax attributes: overlarge attribute name") Right (BS.elemIndex equals keyArea) let prologue = lengthBytes + keyLength + 1 valueBytes = fromIntegral lineLength - prologue if valueBytes == 0 then Left "Malformed pax attributes" else Right (PaxRecord (BS.take keyLength keyArea) prologue (fromIntegral valueBytes - 1))-- | The length a record opens with, and the bytes it and the space after-- it take.paxLength :: ByteString -> Either Text (Int64, Int)paxLength = go 0 0 where go :: Int64 -> Int -> ByteString -> Either Text (Int64, Int) go !acc !used bytes = case BS.uncons bytes of Nothing -> Left "Ignoring malformed pax attributes: overlarge attribute size field" Just (c, rest) | c == space -> Right (acc, used + 1) | c < zero || c > nine -> Left "Ignoring malformed pax attributes: malformed attribute size field" | next > paxLineLimit -> Left ("Ignoring malformed pax attribute: size > " <> T.pack (show paxLineLimit)) | otherwise -> go next (used + 1) rest where next = acc * 10 + fromIntegral (c - zero)-- | Whether libarchive refuses an attribute in a pax global header, whose-- attributes it would have to apply to every entry after it and does not:-- the ones it acts on in an extended header, exactly or by prefix.refusedGlobally :: ByteString -> BoolrefusedGlobally key = key `elem` exact || any prefixed prefixes where exact = [ "atime", "ctime", "gid", "gname", "hdrcharset", "linkpath", "mtime", "path", "size", "uid", "uname", "GNU.sparse", "LIBARCHIVE.creationtime", "LIBARCHIVE.symlinktype", "RHT.security.selinux", "SCHILY.acl.access", "SCHILY.acl.ace", "SCHILY.acl.default", "SCHILY.dev", "SCHILY.devmajor", "SCHILY.devminor", "SCHILY.fflags", "SCHILY.ino", "SCHILY.nlink", "SCHILY.realsize", "SUN.holesdata" ] prefixes = ["GNU.sparse.", "LIBARCHIVE.xattr.", "SCHILY.xattr."] prefixed prefix = BS.length key > BS.length prefix && prefix `BS.isPrefixOf` key-- ----------------------------------------------------------------------------- An entry's own header-- ----------------------------------------------------------------------------- | Read an entry's own header, with what the headers before it said, and-- go on past its body.entryHeader :: Format -> Pending -> ByteString -> ByteString -> TarStepentryHeader format pending block rest | pendingSparse pending || flag == sparseFlag = failWith "sparse archive members are not supported" | size < 0 = failWith "Tar entry has negative file size" | size > entryLimit = failWith "Tar entry size overflow" | otherwise = case node of Nothing -> TarFile entry (fromIntegral size) (fileContents size rest (\after -> skipping (paddingOf size) 0 after next (TarFail . TarDataFailure))) Just other -> TarOther entry other (bodyAfter other) where flag = typeFlag block headerFormat = case (variantOf block, format) of (VariantGnu, _) -> FormatGnu (VariantUstar, FormatPax) -> FormatPax (VariantUstar, _) -> FormatUstar (VariantOld, _) -> FormatOld -- Names are copied, so no entry holds the chunk its header came in. path = BS.copy $ case pendingPath pending of Just named | not (BS.null named) -> named _ -> headerPath block link = BS.copy $ case pendingLink pending of Just named | not (BS.null named) -> named _ -> fieldString linkNameField block size = fromMaybe (fieldNumber sizeField block) (pendingSize pending) -- A link a GNU long-link header or a pax linkpath gave is set as a hard -- link on any entry that is not a symlink, a regular file or a -- directory among them. givenLink = case pendingLink pending of Just target | flag /= symlinkFlag && flag /= hardLinkFlag -> Just (BS.copy target) _ -> Nothing -- libarchive reads a regular entry whose name ends in a slash as a -- directory, with no body, when its headers gave no warning. endsInSlash = maybe False ((== slash) . snd) (BS.unsnoc path) asDirectory = regular && endsInSlash && isNothing (pendingWarning pending) -- Whether the type flag is one libarchive reads as a regular file. regular = flag `notElem` [hardLinkFlag, symlinkFlag, charDeviceFlag, blockDeviceFlag, directoryFlag, fifoFlag, dumpDirFlag] -- What the entry is, when it is not a regular file. node | Just target <- givenLink = Just (TarHardLink target) | flag == hardLinkFlag = Just (TarHardLink link) | flag == symlinkFlag = Just (TarSymlink link) | flag == charDeviceFlag = Just (TarSpecial characterDeviceType) | flag == blockDeviceFlag = Just (TarSpecial blockDeviceType) | flag == directoryFlag || flag == dumpDirFlag = Just TarDirectory | flag == fifoFlag = Just (TarSpecial fifoType) | asDirectory = Just TarDirectory | otherwise = Nothing entry = TarEntry { tarPath = path, tarExecutable = testBit (fieldNumber modeField block) ownerExecuteBit, tarWarning = pendingWarning pending } next = headers LaterHeader headerFormat noPending -- What follows an entry that is not a regular file. A hard link keeps -- its size by the rules below; the body a regular entry or a dump -- directory has is passed over when the entry is a hard link only -- through a given link. bodyAfter other = case other of TarHardLink _ | flag == hardLinkFlag -> hardLinkBody | hasBody -> skipBody rest TarDirectory | flag == dumpDirFlag -> skipBody rest _ -> next rest hasBody = flag == dumpDirFlag || (regular && not asDirectory) -- A hard link's size counts in a pax archive and not in a GNU or old -- one. In a ustar archive it counts unless libarchive's bidder takes -- the link's own header, which a standard ustar header always is. hardLinkBody | size == 0 = next rest | otherwise = case headerFormat of FormatPax -> skipBody rest FormatGnu -> next rest FormatOld -> next rest FormatUstar | bidsAsHeader block -> next rest | otherwise -> skipBody rest -- A body no reader asks for is passed over when the next header is -- read, which a short input fails without naming an entry. skipBody bytes = skipping (padded size) 0 bytes next (TarFail . TarHeaderFailure Nothing) failWith = TarFail . TarHeaderFailure (Just path)-- | The owner's execute bit of a mode.ownerExecuteBit :: IntownerExecuteBit = 6-- | libarchive's file types for the entries upstream refuses, as its-- refusal prints them.characterDeviceType, blockDeviceType, fifoType :: IntcharacterDeviceType = 0o020000blockDeviceType = 0o060000fifoType = 0o010000-- ----------------------------------------------------------------------------- Reading bytes-- ----------------------------------------------------------------------------- | Collect exactly @n@ bytes from what is left of the last chunk and then-- from chunks fed, handing them on with what follows them, or handing on-- what was collected when the input ends first.collect :: Int -> ByteString -> (ByteString -> ByteString -> TarStep) -> (ByteString -> TarStep) -> TarStepcollect n leftover got short | BS.length leftover >= n = uncurry got (BS.splitAt n leftover) | otherwise = go [leftover] (BS.length leftover) where go held have = TarAwait (fed held have) fed held have chunk | BS.null chunk = short (BS.concat (reverse held)) | have + BS.length chunk >= n = uncurry got (BS.splitAt n (BS.concat (reverse (chunk : held)))) | otherwise = go (chunk : held) (have + BS.length chunk)-- | Hand on at least @n@ bytes of what is left of the last chunk and then-- of chunks fed, none of them passed over, or go on with @short@ when the-- input ends first. What is left of the chunk is handed on as it is, not-- copied, when it holds @n@ bytes already.peeking :: Int -> ByteString -> (ByteString -> TarStep) -> TarStep -> TarSteppeeking n leftover got short | BS.length leftover >= n = got leftover | otherwise = TarAwait $ \chunk -> if BS.null chunk then short else peeking n (leftover <> chunk) got short-- | Pass over the rest of a request for @needed@ bytes, @held@ of which-- are already in hand, then go on with what follows them. When the input-- ends first the request fails in libarchive's words, which count the-- bytes the request asked for and the bytes there were.skipping :: Int64 -> Int64 -> ByteString -> (ByteString -> TarStep) -> (Text -> TarStep) -> TarStepskipping needed held leftover next failed = go (needed - held) leftover where go owed bytes | owed <= fromIntegral (BS.length bytes) = next (BS.drop (fromIntegral owed) bytes) | otherwise = TarAwait $ \chunk -> let remaining = owed - fromIntegral (BS.length bytes) in if BS.null chunk then failed (truncatedInput needed (needed - remaining)) else go remaining chunk-- | libarchive's words for a request to pass over bytes that the input-- ends before.truncatedInput :: Int64 -> Int64 -> TexttruncatedInput needed available = "Truncated input file (needed " <> T.pack (show needed) <> " bytes, only " <> T.pack (show available) <> " available)"-- | A file's @n@ bytes of contents as they arrive, then the archive-- after them, or a failure when the input ends first.fileContents :: Int64 -> ByteString -> (ByteString -> TarStep) -> FileStepfileContents n leftover next = go n leftover where go owed bytes | owed <= fromIntegral (BS.length bytes) = let (slice, rest) = BS.splitAt (fromIntegral owed) bytes in chunk slice (FileEnd (next rest)) | otherwise = chunk bytes (FileAwait (fed (owed - fromIntegral (BS.length bytes)))) fed owed bytes | BS.null bytes = FileFail (TarDataFailure truncatedDataMessage) | otherwise = go owed bytes chunk slice after | BS.null slice = after | otherwise = FileChunk slice after-- | libarchive's words for an archive that ends inside an entry's body.truncatedDataMessage :: TexttruncatedDataMessage = "Truncated tar archive detected while reading data"-- ----------------------------------------------------------------------------- Bytes-- ---------------------------------------------------------------------------space, tab, minus, zero, seven, nine, equals, lineFeed, slash, upperA, upperZ, lowerA, lowerZ :: Word8space = 0x20tab = 0x09minus = 0x2dzero = 0x30seven = 0x37nine = 0x39equals = 0x3dlineFeed = 0x0aslash = 0x2fupperA = 0x41upperZ = 0x5alowerA = 0x61lowerZ = 0x7a-- | The type flags the reader acts on.hardLinkFlag, symlinkFlag, charDeviceFlag, blockDeviceFlag, directoryFlag, fifoFlag, dumpDirFlag, sparseFlag, aclFlag, globalFlag, longLinkFlag, longNameFlag, volumeFlag, sunPaxFlag, paxFlag :: Word8hardLinkFlag = 0x31symlinkFlag = 0x32charDeviceFlag = 0x33blockDeviceFlag = 0x34directoryFlag = 0x35fifoFlag = 0x36dumpDirFlag = 0x44sparseFlag = 0x53aclFlag = 0x41globalFlag = 0x67longLinkFlag = 0x4blongNameFlag = 0x4cvolumeFlag = 0x56sunPaxFlag = 0x58paxFlag = 0x78