hascar (empty) → 0.1.0.0
raw patch · 12 files changed
+1319/−0 lines, 12 filesdep +ansi-wl-pprintdep +arraydep +attoparsecsetup-changed
Dependencies added: ansi-wl-pprint, array, attoparsec, base, binary, bytestring, conduit, containers, cryptohash, directory, exceptions, filepath, gitrev, hascar, hex, mtl, optparse-applicative, path, pretty-show, text, time, transformers, unix
Files
- LICENSE +90/−0
- Setup.hs +2/−0
- app/GPL.hs +56/−0
- app/Main.hs +95/−0
- app/Options.hs +63/−0
- hascar.cabal +77/−0
- src/Codec/Archive/SAPCAR.hs +385/−0
- src/Codec/Archive/SAPCAR/BitStream.hs +120/−0
- src/Codec/Archive/SAPCAR/CanonicalHuffmanTree.hs +162/−0
- src/Codec/Archive/SAPCAR/FlatedFile.hs +184/−0
- src/Codec/Archive/SAPCAR/FlexibleUtils.hs +48/−0
- test/Spec.hs +37/−0
+ LICENSE view
@@ -0,0 +1,90 @@+GNU GENERAL PUBLIC LICENSE+Version 2, June 1991++Copyright (C) 1989, 1991 Free Software Foundation, Inc.+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA++Everyone is permitted to copy and distribute verbatim copies+of this license document, but changing it is not allowed.++Preamble++The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.++When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.++To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.++For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.++We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.++Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.++Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.++The precise terms and conditions for copying, distribution and modification follow.++TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.++1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.++You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.++2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:++a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.++b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.++c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.++In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.++3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:++a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)+The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.++If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.++4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.++5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.++6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.++7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.++This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.++8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.++9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.++Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.++10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.++NO WARRANTY++11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.++END OF TERMS AND CONDITIONS
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ app/GPL.hs view
@@ -0,0 +1,56 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+module GPL+ ( gpl+ , gpl'+ , putGpl+ ) where++import Control.Monad+import Data.Text (Text)+import Development.GitRev+import Text.PrettyPrint.ANSI.Leijen++import qualified Data.Text as T+import qualified Data.Text.IO as TI++-- | The copyright text+gpl' :: [Text]+gpl' =+ [ "hascar, Copyright (C) 2016, Virtual Forge GmbH.", ""+ , "Maint.: Hans-Christian Esperer"+ , "<hans-christian.esperer@virtualforge.com>", ""+ , "hascar comes with ABSOLUTELY NO WARRANTY;"+ , "for details read the LICENSE file."+ , "This is free software, and you are welcome to redistribute"+ , "it under certain conditions; see the LICENSE file for details." ]++-- | Print the header to the screen+putGpl :: IO ()+putGpl = putDoc gpl >> putStrLn ""++-- | Nicely formatted copyright text+gpl :: Doc+gpl = hsep . map (\l -> text (T.unpack l) <> line) $ lines+ where+ header = " ┌────────────────────────────────────────────────────────────────────┐"+ lines :: [Text]+ lines = [ header ] ++ map pad gpl' ++ map pad+ [ "", T.pack version ] ++ [ footer ]+ footer = "└────────────────────────────────────────────────────────────────────┘"++-- | Center a text with box characters at the leftmost+-- and rightmost position+pad :: Text -> Text+pad line = T.concat [ "│", padl', line, padr', "│" ]+ where+ len = T.length line+ padl = (68 - len) `quot` 2+ padr = if padl + padl + len == 68+ then padl+ else padl + 1+ padl' = T.replicate padl " "+ padr' = T.replicate padr " "++version :: String+version = "hascar " ++ take 8 $(gitHash) ++ " revision " ++ $(gitCommitCount) ++ " on branch " ++ $(gitBranch)
+ app/Main.hs view
@@ -0,0 +1,95 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+-- |+-- (De-)compress SAPCAR files+--+-- Copyright (C) 2016, Virtual Forge GmbH+--+-- This program is free software; you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation; either version 2 of the License, or (at+-- your option) any later version.+--+-- This program is distributed in the hope that it will be useful, but+-- WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+-- General Public License for more details.+--+-- You should have received a copy of the GNU General Public License+-- along with this program; if not, write to the Free Software+-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307+-- USA+module Main where++import Control.Monad+import Control.Monad.IO.Class+import Data.Binary.Get+import Path+import System.Directory+import System.Environment+import System.FilePath+import System.IO+import Text.Show.Pretty++import qualified Data.ByteString as S+import qualified Data.ByteString.Lazy as L+import qualified Data.Text as T++import Options++import Codec.Archive.SAPCAR++#ifndef mingw32_HOST_OS+import System.Posix.Files as SPF+#endif+import System.Posix.Types (CMode(..))++-- |Main entry point+main :: IO ()+main = runWithHeader it++it :: Options -> IO ()+it options = do+ withSapCarFile (oFilename options) $ do+ entries <- getEntries+ let files = ((== CarFile) . cfFileType) `filter` entries+ let dirs = ((== CarDirectory) . cfFileType) `filter` entries+ unless (oQuiet options) . liftIO . putStrLn $ show (length entries) ++ " entrie(s) in the archive."++ when (oListEntries options) $ liftIO $ do+ putStrLn "\nAll entries:"+ forM_ entries (putStrLn . ppShow)+ putStrLn ""++ when (oDecompress options) $ do+ forM_ dirs $ \dir -> do+ dirname <- parseRelDir $ T.unpack $ carEntryFilename dir+ when (oVerbose options) $+ liftIO $ putStrLn $ "Creating " ++ show dirname+ liftIO $ do+ createDirectoryIfMissing True $ fromRelDir dirname+#ifndef mingw32_HOST_OS+ SPF.setFileMode (fromRelDir dirname) $ CMode $ cfPermissions dir+#endif++ forM_ files $ \file -> do+ filename <- parseRelFile $ T.unpack $ carEntryFilename file+ liftIO $ cdim $ fromRelFile filename+ when (oVerbose options) $+ liftIO $ putStrLn $ "Extracting " ++ show filename+ writeToFile file filename+#ifndef mingw32_HOST_OS+ liftIO $ SPF.setFileMode (fromRelFile filename) $ CMode $ cfPermissions file+#endif+++cdim :: FilePath -> IO ()+cdim fp = do+ let fpt = T.pack fp+ parts = T.split (== pathSeparator) fpt++ when (length parts > 1) $ do+ let path = T.unpack $ T.intercalate (T.pack [pathSeparator]) $ take (length parts - 1) parts+ p <- parseRelDir path+ createDirectoryIfMissing True $ fromRelDir p+
+ app/Options.hs view
@@ -0,0 +1,63 @@+module Options+ ( Options(..)+ , run+ , runWithHeader+ ) where++import Options.Applicative++import qualified Data.Text as T++import GPL++-- |HASCAR runtime options+data Options = Options+ { -- | Filename of the SAPCAR archive+ oFilename :: !FilePath+ , -- | Whether to extract the archive's contents+ oDecompress :: !Bool+ , -- | Whether to print verbose information during operation+ oVerbose :: !Bool+ , -- | Whether to suppress printing the GPL header and other info+ oQuiet :: !Bool+ , -- | Whether to list all entries in the archive+ oListEntries :: !Bool+ } deriving (Show)++runWithHeader :: (Options -> IO a) -> IO a+runWithHeader o = run (\l -> putGpl >> o l)++run :: (Options -> IO a) -> IO a+run = (>>=) (execParser spec)++spec :: ParserInfo Options+spec = info (helper <*> optionsParser)+ ( fullDesc+ <> progDesc "Decompress SAPCAR archives"+ <> headerDoc (Just gpl) )++optionsParser :: Parser Options+optionsParser = Options+ <$> option str+ ( metavar "SAPCARFILE"+ <> short 'f'+ <> long "file"+ <> help "Path to the SAPCAR file" )+ <*> switch+ ( long "extract"+ <> short 'x'+ <> help "Extract archive contents into current directory" )+ <*> switch+ ( long "verbose"+ <> short 'v'+ <> help "Verbose operation" )+ <*> switch+ ( long "quiet"+ <> short 'q'+ <> help "Do not print the header" )+ <*> switch+ ( long "list"+ <> short 't'+ <> help "List all entries in the archive" )++
+ hascar.cabal view
@@ -0,0 +1,77 @@+name: hascar+version: 0.1.0.0+synopsis: Decompress SAPCAR archives+description: Please see README.md+homepage: https://github.com/VirtualForgeGmbH/hascar+license: GPL-2+license-file: LICENSE+author: Hans-Christian Esperer <hc@hcesperer.org>+maintainer: Hans-Christian Esperer <hc@hcesperer.org>+copyright: 2016, Virtual Forge GmbH+category: Cabal+build-type: Simple+-- extra-source-files:+cabal-version: >=1.10++library+ hs-source-dirs: src+ exposed-modules: Codec.Archive.SAPCAR+ other-modules: Codec.Archive.SAPCAR.BitStream+ , Codec.Archive.SAPCAR.CanonicalHuffmanTree+ , Codec.Archive.SAPCAR.FlatedFile+ , Codec.Archive.SAPCAR.FlexibleUtils+ build-depends: base >= 4.7 && < 5+ , array >= 0.5.1.0 && < 0.6+ , attoparsec >= 0.13.0.2 && < 0.14+ , binary >= 0.7.5.0 && < 0.8+ , bytestring >= 0.10.6.0 && < 0.11+ , containers >= 0.5.6.2 && < 0.6+ , conduit >= 1.2.6.6 && < 1.3+ , exceptions >= 0.8.2.1 && < 0.9+ , mtl >= 2.2.1 && < 2.3+ , path >= 0.5.7 && < 0.6+ , pretty-show >= 1.6.10 && < 1.7+ , text >= 1.2.2.1 && < 1.3+ , time >= 1.5.0.1 && < 1.6+ default-language: Haskell2010++executable hascar+ hs-source-dirs: app+ main-is: Main.hs+ other-modules: GPL+ , Options+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ build-depends: base+ , ansi-wl-pprint >= 0.6.7.3 && < 0.7+ , binary >= 0.7.5.0 && < 0.8+ , bytestring >= 0.10.6.0 && < 0.11+ , directory >= 1.2.2.0 && < 1.3+ , filepath >= 1.4.0.0 && < 1.5+ , gitrev >= 1.2.0 && < 1.3+ , hascar+ , optparse-applicative >= 0.12.1.0 && < 0.13+ , path >= 0.5.7 && < 0.6+ , pretty-show >= 1.6.10 && < 1.7+ , text >= 1.2.2.1 && < 1.3+ , transformers >= 0.4.2.0 && < 0.5+ if !os(windows)+ build-depends: unix >= 2.7.1.0 && < 2.8+ default-language: Haskell2010++test-suite hascar-test+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Spec.hs+ build-depends: base+ , bytestring+ , conduit+ , cryptohash+ , hascar+ , hex+ , path+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ default-language: Haskell2010++source-repository head+ type: git+ location: https://github.com/githubuser/hascar
+ src/Codec/Archive/SAPCAR.hs view
@@ -0,0 +1,385 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ExistentialQuantification #-}+-- |+-- (De-)compress SAPCAR files+--+-- Copyright (C) 2016, Virtual Forge GmbH+--+-- This program is free software; you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation; either version 2 of the License, or (at+-- your option) any later version.+--+-- This program is distributed in the hope that it will be useful, but+-- WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+-- General Public License for more details.+--+-- You should have received a copy of the GNU General Public License+-- along with this program; if not, write to the Free Software+-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307+-- USA+module Codec.Archive.SAPCAR+ ( SapCar+ , CarEntry (..)+ , CarFileType (..)+ , carEntryFilename+ , withSapCarFile+ , withSapCarPath+ , withSapCarHandle+ , getEntries+ , sourceEntry+ , writeToFile+ , writeToHandle+ ) where++import Control.Monad+import Control.Monad.State.Strict+import Control.Monad.Catch+import Data.Binary.Get+import Data.Binary.Put+import Data.Bits+import Data.Conduit+import Data.Int+import Data.Word+import Data.Text (Text)+import Data.Time.Clock.POSIX+import Data.Time.Format+import Path+import System.IO+import Text.Printf+import Text.Show.Pretty++import qualified Data.ByteString as S+import qualified Data.ByteString.Lazy as L+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE++import qualified Codec.Archive.SAPCAR.FlatedFile as FF++-- | The SAPCAR monad. All operations on SAPCAR files+-- should happen inside this monad.+type SapCar m a = StateT SapCarFile m a++-- | The state during operations inside the SAPCAR monad.+data SapCarFile = SapCarFile+ { -- | The handle to the open SAPCAR file+ sarFileH :: !Handle+ }++-- | The SAPCAR file header+data SapCarHeader = SapCarHeader+ { -- | The version string of the SAPCAR archive+ scVersion :: !Text+ , -- | Meta information on all files and directories in an archive+ scFiles :: ![CarEntry]+ } deriving (Show)++-- | The type of an entry in the SAPCAR file+data CarFileType+ = -- | A regular file+ CarFile+ | -- | A directory+ CarDirectory+ | -- | Something else+ CarUnknown+ deriving (Show, Eq, Enum)++-- | Get the type of an entry in the SAPCAR file+getType :: Get CarFileType+getType = getType' <$> getByteString 2+ where+ getType' t+ | t == "RG" = CarFile+ | t == "DR" = CarDirectory+ | otherwise = CarUnknown++-- | Meta information about a single file or directory+-- in a SAPCAR archive+data CarEntry = CarEntry+ { -- | The type of the entry+ cfFileType :: !CarFileType+ , -- | The unix style permissions of the entry+ cfPermissions :: !Word32+ , -- | The uncompressed length of the whole file, if it is a file+ cfLength :: !Word32+ , -- | The EPOCH timestamp of the file+ cfTimestamp :: !Word32+ , -- | The filename+ cfFileName :: !Text+ , -- | The absolute offset of the entry in the SAPCAR file+ cfFileOffset :: !Int64+ , -- | The absolute offset of the payload of the entry+ cfPayloadOffset :: !Int64+ }++instance Show CarEntry where+ show ce = printf "%s%s 0 root root %d\t%s 00:00 %s"+ (case cfFileType ce of+ CarFile -> "-" :: Text+ CarDirectory -> "d"+ CarUnknown -> "X")+ (toPermissionText $ cfPermissions ce)+ (cfLength ce)+ (unparseDate $ cfTimestamp ce)+ (cfFileName ce)++-- | Convert an EPOCH date to a string+-- that is compatible to the output of the UNIX(R)+-- "ls -l" command+unparseDate :: Word32 -> String+unparseDate = formatTime defaultTimeLocale "%b %e" . posixSecondsToUTCTime . fromIntegral++-- | Convert UNIX permissions to a string+-- that is compatible to the output of the UNIX(R)+toPermissionText :: Word32 -> Text+toPermissionText n = T.concat [u, g, o]+ where+ u = toPermissionText' $ n `shiftR` 6 .&. 7+ g = toPermissionText' $ n `shiftR` 3 .&. 7+ o = toPermissionText' $ n .&. 7++toPermissionText' :: Word32 -> Text+toPermissionText' n = T.concat [r `perm` "r", w `perm` "w", x `perm` "x"]+ where+ x = n .&. 1 == 1+ w = n `shiftR` 1 .&. 1 == 1+ r = n `shiftR` 2 .&. 1 == 1++perm :: Bool -> Text -> Text+perm True w = w+perm False w = "-"++-- | Get the filename of a car entry+carEntryFilename :: CarEntry -> Text+carEntryFilename = cfFileName++-- | The compression algorithm used+data CompAlg+ = -- | Lempel-Ziv huffman+ CompLzh+ | -- | LZC+ CompLzc+ | -- | Something else+ CompUnknown+ deriving (Show, Eq, Enum)++-- | The header of one compressed SAPCAR block.+-- This is not to be confused with a single compressed+-- block! One SAPCAR block usually contains one or two+-- lzh blocks. Yes, it's confusing and not yielding the+-- best compression ratio...+data CompHdr = CompHdr+ { -- | The length.+ chLen :: !Word32+ , -- | The used algorithm. This is indeed encoded for each block.+ chAlg :: !CompAlg+ , -- | The magic number.+ chMagic :: !Word16+ , -- | The special byte. Meaning depends on the CompAlg.+ chSpe :: !Word8+ } deriving (Show)+++-- | Run all actions in the SapCar monad.+withSapCarPath+ :: (MonadIO m, MonadThrow m, MonadMask m)+ => Path b File+ -> SapCar m a+ -> m a+withSapCarPath sarfile = bracket open close . withSapCarHandle+ where+ open = liftIO $ openBinaryFile (toFilePath sarfile) ReadMode+ close = liftIO . hClose++-- | Run all actions in the SapCar monad.+withSapCarFile+ :: (MonadIO m, MonadThrow m, MonadMask m)+ => FilePath+ -> SapCar m a+ -> m a+withSapCarFile sarfile = bracket open close . withSapCarHandle+ where+ open = liftIO $ openBinaryFile sarfile ReadMode+ close = liftIO . hClose++-- | Run all actions in the SapCar monad.+withSapCarHandle+ :: (MonadIO m, MonadThrow m, MonadMask m)+ => SapCar m a+ -> Handle+ -> m a+withSapCarHandle a = evalStateT a . SapCarFile++-- let res = runGet (parseFileHdr >> parseSAPCARFile []) c++-- | Get all entries contained inside the SapCar file.+getEntries :: MonadIO m => SapCar m [CarEntry]+getEntries = do+ fh <- sarFileH <$> get+ let entryParser = runGetIncremental (parseFileHdr >> parseSAPCARFile [])+ res <- liftIO $ feedChunks entryParser fh+ let Done _ _ entries = res+ return entries++-- | Stream the contents of the given SapCar entry to+-- the specified conduit sink.+sourceEntry :: MonadIO m => CarEntry -> Sink S.ByteString IO a -> SapCar m a+sourceEntry entry sink = do+ fh <- sarFileH <$> get+ case cfLength entry of+ 0 -> liftIO $ emptySource $$ sink+ _ -> do+ liftIO $ hSeek fh AbsoluteSeek $ fromIntegral $ cfPayloadOffset entry+ liftIO $ decompressBlocks fh $$ sink++emptySource :: Source IO S.ByteString+emptySource = yield ""++-- | Feed chunks of data to the Get monad+feedChunks :: Decoder a -> Handle -> IO (Decoder a)+feedChunks d h = do+ chunk <- S.hGet h 8192+ if chunk == S.empty+ then return $ pushEndOfInput d+ else feedChunks (pushChunk d chunk) h++-- | Parse all SAPCAR entries. (tail recursive)+parseSAPCARFile :: [CarEntry] -> Get [CarEntry]+parseSAPCARFile acc = do+ empty <- isEmpty+ if empty+ then return acc+ else do+ entry <- parseEntry+ parseSAPCARFile $ entry:acc++-- | Write a SapCar entry to the specified file.+writeToFile :: (MonadIO m, MonadMask m, MonadThrow m) => CarEntry -> Path b File -> SapCar m ()+writeToFile entry path = bracket open close w+ where+ open = liftIO $ openBinaryFile (toFilePath path) WriteMode+ close = liftIO . hClose+ w = sourceEntry entry . writer++-- | Write a SapCar entry to the specified handle.+writeToHandle :: (MonadIO m, MonadMask m, MonadThrow m) => CarEntry -> Handle -> SapCar m ()+writeToHandle entry = sourceEntry entry . writer++-- | Provide a conduit sink, write everything that arrives there to the given handle.+writer :: Handle -> Sink S.ByteString IO ()+writer h = do+ chunk <- await+ case chunk of+ Just chunk' -> do+ liftIO $ do+ -- S.hPut h "================== BEGIN CHUNK =======================================\n"+ S.hPut h chunk'+ -- S.hPut h "\n============================ END CHUNK ===============================\n"+ writer h+ Nothing -> return ()++-- | Parse the compression header of one SAPCAR block.+parseCompHdr :: Get CompHdr+parseCompHdr = do+ len <- getWord32le+ alg <- getWord8+ let alg' = case alg of+ 18 -> CompLzh+ 16 -> CompLzc+ _ -> CompUnknown+ magic <- getWord16be+ when (magic /= 8093) $ error $ "Invalid magic value (8093 decimal expected); got " ++ show magic+ spe <- getWord8+ return $ CompHdr len alg' magic spe++-- | Parse one SAPCAR entry's metadata, ignoring its contents.+parseEntry :: Get CarEntry+parseEntry = do+ fileOffset <- bytesRead+ ftype <- getType+ fperm <- getWord32le+ flen <- getWord32le+ void $ getByteString 8+ ftimestamp <- getWord32le+ void $ getByteString 10+ fnlen <- fromIntegral <$> getWord16le+ fn <- getByteString $ fnlen - 1+ nulbyte <- getWord8+ when (nulbyte /= 0) $ error "NUL byte expected"+ case ftype of+ CarFile -> do+ payloadOffset <- bytesRead+ unless (flen == 0) skipBlocks+ return $ CarEntry ftype fperm flen ftimestamp (TE.decodeUtf8 fn) fileOffset payloadOffset+ CarDirectory ->+ return $ CarEntry ftype fperm flen ftimestamp (TE.decodeUtf8 fn) fileOffset 0+ _ -> error $ "Unhandled type " ++ show ftype++-- | Skip all SAPCAR payload blocks for one SAPCAR entry.+skipBlocks :: Get ()+skipBlocks = do+ ed <- getByteString 2+ skipBlock+ case ed of+ "ED" -> getWord32le >> return ()+ "UE" -> getWord32le >> return ()+ "DA" -> skipBlocks+ "UD" -> skipBlocks+ _ -> error $ "Unknown block type " ++ show ed++-- | Skip one SAPCAR payload block.+skipBlock :: Get ()+skipBlock = void (getWord32le >>= getByteString . fromIntegral)++-- | Decompress all SAPCAR blocks of one SAPCAR entry.+decompressBlocks :: Handle -> Source IO S.ByteString+decompressBlocks h = do+ ed <- liftIO $ S.hGet h 2+ case ed of+ -- Compressed block (any algorithm; last block)+ "ED" -> do+ (liftIO $ decompressBlock h) >>= yield+ void $ liftIO $ S.hGet h 4 -- TODO: This is the crc value. Use it!++ -- Compressed block (any algorithm; more to follow)+ "DA" -> do+ (liftIO $ decompressBlock h) >>= yield+ -- liftIO $ print blocks+ decompressBlocks h++ -- Uncompressed block (more to follow)+ "UD" -> do+ (liftIO $ uncompressedBlock h) >>= yield+ decompressBlocks h++ -- Uncompressed block (last block)+ -- Looks like uncompressed files don't have a CRC appended+ "UE" -> (liftIO $ uncompressedBlock h) >>= yield++ _ -> error $ "(while decompressing) unknown block type " ++ show ed++-- | Handle one SAPCAR block that is stored uncompressed+uncompressedBlock :: Handle -> IO S.ByteString+uncompressedBlock h = do+ blockSize <- S.hGet h 4+ let blockSize' = runGet getWord32le $ L.fromStrict blockSize+ S.hGet h $ fromIntegral blockSize'++-- | Handle one SAPCAR block that consists of+-- *one or more* compressed blocks of any supported+-- compression algorithm.+decompressBlock :: Handle -> IO S.ByteString+decompressBlock h = do+ hdr <- L.fromStrict <$> S.hGet h 12+ let (fCompLen, compHdr) = runGet ((,) <$> getWord32le <*> parseCompHdr) hdr+ when (chAlg compHdr /= CompLzh) $ error "Currently only LZH is supported, not LZC"+ blob <- S.hGet h $ fromIntegral fCompLen - 8+ return $ FF.decompressBlock blob++-- | Parse (ignore, for now) the SAPCAR global header+parseFileHdr :: Get ()+parseFileHdr = do+ hdr <- getByteString 8+ unless (hdr == "CAR 2.01") $ error "Only the newest SAPCAR format (2.01) is supported"+
+ src/Codec/Archive/SAPCAR/BitStream.hs view
@@ -0,0 +1,120 @@+-- |+-- Module: BitStream+-- Copyright: (C) 2015, Virtual Forge GmbH+-- License: GPL@+-- Maintainer: Hans-Christian Esperer <hc@hcesperer.org>+-- Stability: experimental+-- Portability: portable+-- |+-- (De-)compress SAPCAR files+--+-- Copyright (C) 2016, Virtual Forge GmbH+--+-- This program is free software; you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation; either version 2 of the License, or (at+-- your option) any later version.+--+-- This program is distributed in the hope that it will be useful, but+-- WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+-- General Public License for more details.+--+-- You should have received a copy of the GNU General Public License+-- along with this program; if not, write to the Free Software+-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307+-- USA+module Codec.Archive.SAPCAR.BitStream+ ( BitStream+ , makeStream+ , getBits+ , consume+ , getAndConsume+ , Codec.Archive.SAPCAR.BitStream.isEmpty+ , getRest+ ) where++import Control.Monad.State.Strict+import Data.Bits+import Data.ByteString+import Data.ByteString.Char8+import Data.Char++import Debug.Trace++-- |Opaque data type that contains a bitstream+data BitStream = BitStreamy+ { bytes :: !ByteString+ , number :: !Int+ , offset :: !Int+ } deriving (Show)++-- |Make a bitstream out of a ByteString+makeStream :: ByteString -> BitStream+makeStream theBytes = BitStreamy+ { bytes=theBytes+ , number=0+ , offset=0 }++getBits_ :: BitStream -> Int -> (BitStream, Int)+getBits_ stream numBits =+ if numBits > offset stream+ then getBits_ newStream numBits+ else (consumedStream, bits)+ where+ newStream = stream { number=number stream .|. byte `shiftL` offset stream,+ offset=offset stream + 8,+ bytes=Data.ByteString.Char8.tail $ bytes stream }+ byte = ord . Data.ByteString.Char8.head $ bytes stream+ consumedStream = stream -- { number=newNumber }+ newNumber = if numBits == 32+ then 0+ else number stream `shiftR` numBits+ bits = number stream .&. ((1 `shiftL` numBits) - 1)++-- |Return the specified number of bits from a BitStream,+-- converted to an integer using big endian coding+getBits :: Int -> State BitStream Int+getBits 0 = return 0+getBits numBits = do+ stream <- get+ let (newstream, result) = getBits_ stream numBits+ put newstream+ return result++consume_ :: BitStream -> Int -> BitStream+consume_ stream numBits =+ stream { offset=offset stream - numBits,+ number=if numBits == 32+ then 0+ else number stream `shiftR` numBits }++-- |Consume the specified number of bits+consume :: Int -> State BitStream ()+consume numBits = do+ stream <- get+ put $ consume_ stream numBits++getAndConsume_ :: BitStream -> Int -> (BitStream, Int)+getAndConsume_ stream numBits = (newStream, bits)+ where+ (stream', bits) = getBits_ stream numBits+ newStream = consume_ stream' numBits++-- |A combination of the getBits and consume functions+getAndConsume :: Int -> State BitStream Int+getAndConsume 0 = return 0+getAndConsume numBits = do+ stream <- get+ let (newstream, bits) = getAndConsume_ stream numBits+ put newstream+ return bits++-- | Is the BitStream empty?+isEmpty :: State BitStream Bool+isEmpty = (== empty) . bytes <$> get++-- | Return a new BitStream that contains the unread+-- rest of the given BitStream.+getRest :: State BitStream BitStream+getRest = get
+ src/Codec/Archive/SAPCAR/CanonicalHuffmanTree.hs view
@@ -0,0 +1,162 @@+-- |+-- Module: CanonicalHuffmanTree+-- Copyright: (C) 2015, Virtual Forge GmbH+-- License: GPL2+-- Maintainer: Hans-Christian Esperer <hc@hcesperer.org>+-- Stability: experimental+-- Portability: portable+-- |+-- (De-)compress SAPCAR files+--+-- Copyright (C) 2016, Virtual Forge GmbH+--+-- This program is free software; you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation; either version 2 of the License, or (at+-- your option) any later version.+--+-- This program is distributed in the hope that it will be useful, but+-- WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+-- General Public License for more details.+--+-- You should have received a copy of the GNU General Public License+-- along with this program; if not, write to the Free Software+-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307+-- USA+module Codec.Archive.SAPCAR.CanonicalHuffmanTree+ (CanonicalHuffmanTree, makeHuffmanTree,+ getEntry, CHTEntry, readEntry,+ litcode, eobcode,+ value, numBits, numExtraBits,+ isLitcode, isEobcode, readEntryRaw) where++import Control.Applicative+import Control.Monad.State.Strict+import Data.Bits+import Data.List+import GHC.Arr++import Codec.Archive.SAPCAR.BitStream+import Codec.Archive.SAPCAR.FlexibleUtils++-- |A data structure representing a particular huffman tree entry+data CHTEntry = CHTEntry {+ -- |The value this entry encodes+ value :: !Int+ -- |The "weight" of this entry+ , sortindex :: !Int+ -- |The number of extra bits that need to be read to decode the value+ -- encoded partially by this huffman tree entry+ , numExtraBits :: !Int+ -- |The number of bits required to encode this huffman tree entry+ , numBits :: !Int+ -- |The bits representing this huffman tree entry+ , bits :: !Int+ } | CHTInvalid deriving (Eq, Show)++-- |A data structure representing a canonical huffman tree+data CanonicalHuffmanTree = CHT (GHC.Arr.Array Int CHTEntry) Int deriving (Show)++instance Ord CHTEntry where+ compare a b+ | numBits a < numBits b = LT+ | numBits a > numBits b = GT+ | sortindex a < sortindex b = LT+ | sortindex a > sortindex b = GT+ | otherwise = EQ++-- |Get a particular entry from a CanonicalHuffmanTree+getEntry :: CanonicalHuffmanTree -> Int -> CHTEntry+getEntry (CHT arry _) idx = arry ! idx++-- |Read one entry from a bitstream using the given+-- CanonicalHuffmanTree, returning the entry in the+-- huffman tree, not the value it encodes+readEntryRaw :: CanonicalHuffmanTree -> State BitStream CHTEntry+readEntryRaw (CHT arry maxNumBits) = do+ bits' <- getBits maxNumBits+ let entry = arry ! bits'+ consume $ numBits entry+ return entry++-- |Read one entry from a bitstream using the given+-- CanonicalHuffmanTree+readEntry :: CanonicalHuffmanTree -> State BitStream Int+readEntry cht = value <$> readEntryRaw cht++-- |A constant for literal entries+litcode :: Int+litcode = 16++-- |A constant meaning "end of bitstream"+eobcode :: Int+eobcode = 15++-- |Is the specified integer the special value+-- for "literal entries"?+isLitcode :: Int -> Bool+isLitcode = (== litcode)++-- |Is the specified integer the special value+-- indicating "end of bitstream"?+isEobcode :: Int -> Bool+isEobcode = (== eobcode)++-- |Make a huffman tree. Takes a list of the bit lengths, the number of+-- "regular" entries (integer values counting from zero), plus a list of+-- additional entries and a list of extra lengths+makeHuffmanTree :: [Int] -> Int -> [Int] -> [Int] -> CanonicalHuffmanTree+makeHuffmanTree bitLengths countRegular extraBits' extraLengths = CHT chtArray maximumLength+ where+ chtArray = makeFlexArray (0, maximum . map fst $ chtentries''') CHTInvalid chtentries'''+ chtentries = sort . map mkChtEntry . enumerate $ zip3 values extraBits bitLengths+ chtentries' = filter ((/= 0) . numBits) chtentries+ (_, _, chtentries'') = foldl assignBitValue (-1, 1, []) chtentries'+ chtentries''' = concatMap fillEmUp chtentries''+ fillEmUp entry' = map (fillIt entry') [0..max' - 1]+ where+ max' = shiftL 1 padBits+ padBits = maximumLength - numBits entry'+ entryVal = reverseBits (bits entry') (numBits entry')+ fillIt entry i = (entryVal + i `shiftL` numBits entry, entry)+ assignBitValue (lastbitval, lastbitlen, entries) entry =+ (bitval, bitlen, newentry:entries)+ where+ bitval+ | bitlen > lastbitlen && lastbitval == -1 = 0+ | bitlen > lastbitlen = inc `shiftL` incBy+ | otherwise = lastbitval + 1+ inc = lastbitval + 1+ incBy = bitlen - lastbitlen+ bitlen = numBits entry+ newentry = entry { bits=bitval }+ mkChtEntry :: (Int, (Int, Int, Int)) -> CHTEntry+ mkChtEntry (i, (value', numextraBits, bitLength)) = CHTEntry {+ value=value',+ sortindex=i,+ numExtraBits=numextraBits,+ numBits=bitLength,+ bits= -1}+ maximumLength = maximum bitLengths+ (values, extraBits) = unzip pairs+ pairs = map genValues . enumerate $ regulars ++ zip extraBits' extraLengths+ enumerate = zip [0..]+ regulars = enumerate [0..countRegular - 1]+ genValues (i,(j,k))+ | i < countRegular && i < 256 = (i, litcode)+ | i < countRegular = (i, eobcode)+ | otherwise = (j, k)++reverseBits :: Int -> Int -> Int+reverseBits x numBits' = result+ where+ (_, result) = foldl step (x, 0) [1..numBits']+ step (y, s) _ = (newY, newS)+ where+ newY = y `shiftR` 1+ newS+ | lowestY == 1 = s `shiftL` 1 + 1+ | otherwise = s `shiftL` 1+ lowestY = y .&. 1+
+ src/Codec/Archive/SAPCAR/FlatedFile.hs view
@@ -0,0 +1,184 @@+{-# LANGUAGE OverloadedStrings #-}+-- |+-- Module: FlatedFile+-- Copyright: (C) 2015-2016, Virtual Forge GmbH+-- License: GPL2+-- Maintainer: Hans-Christian Esperer <hans-christian.esperer@virtualforge.com>+-- Stability: experimental+-- Portability: portable+-- |+-- (De-)compress SAPCAR files+--+-- Copyright (C) 2016, Virtual Forge GmbH+--+-- This program is free software; you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation; either version 2 of the License, or (at+-- your option) any later version.+--+-- This program is distributed in the hope that it will be useful, but+-- WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+-- General Public License for more details.+--+-- You should have received a copy of the GNU General Public License+-- along with this program; if not, write to the Free Software+-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307+-- USA+module Codec.Archive.SAPCAR.FlatedFile+ ( decompressBlock+ ) where++import Control.Applicative+import Control.Monad+import Control.Monad.State.Strict+import Data.Char+import Data.Foldable (toList)+import Data.Functor.Identity+import Data.Sequence ((><), (|>))+import Data.Word+import System.IO++import qualified Control.Exception as CE+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BSL+import qualified Data.Attoparsec.ByteString.Lazy as DABL+import qualified Data.Sequence as DS++import Codec.Archive.SAPCAR.BitStream+import Codec.Archive.SAPCAR.CanonicalHuffmanTree+import Codec.Archive.SAPCAR.FlexibleUtils++-- Copied from vpa108csulzh.cpp under GPL by SAP AG+border :: [Int]+border = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]++cplens :: [Int]+cplens = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43,+ 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0]++cpdist :: [Int]+cpdist = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257,+ 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289,+ 16385, 24577]++csExtraDistBits :: [Int]+csExtraDistBits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7,+ 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]++csExtraLenBits :: [Int]+csExtraLenBits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3,+ 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99]+-- End copied from vpa108csulzh.cpp under GPL by SAP AG++readInt32Big :: Handle -> IO Int+readInt32Big h = do+ [b1, b2, b3, b4] <- replicateM 4 $ ord <$> hGetChar h+ return $ b1 * 16777216 + b2 * 65536 + b3 * 256 + b4++entryReader :: [[Int]]+ -> CanonicalHuffmanTree+ -> Int+ -> Int+ -> StateT+ BitStream Data.Functor.Identity.Identity [Int]+entryReader entries huft entriesToRead lastEntry+ | (length . concat $ entries) >= entriesToRead = return . concat . reverse $ entries+ | otherwise = do+ entry <- readEntry huft+ newEntries <- handleEntry entry+ entryReader (newEntries:entries) huft entriesToRead $ last newEntries+ where+ handleEntry :: Int -> State BitStream [Int]+ handleEntry code+ | code < 16 = return [code]+ | code == 16 = do+ numRepetitions <- (3 +) <$> getAndConsume 2+ return $ replicate numRepetitions lastEntry+ | code == 17 = do+ numZeroes <- (3 +) <$> getAndConsume 3+ return $ replicate numZeroes 0+ | code == 18 = do+ numZeroes <- (11 +) <$> getAndConsume 7+ return $ replicate numZeroes 0+ | otherwise = error "Corrupted file"+ +decodeIt+ :: CanonicalHuffmanTree+ -> CanonicalHuffmanTree+ -> DS.Seq Word8+ -> State BitStream (DS.Seq Word8)+-- decodeIt lt dt = BS.pack . toList <$> decodeIt' empty+decodeIt lt dt = decodeIt'+ where+ decodeIt' acc = do+ entry <- readEntryRaw lt+ case numExtraBits entry of+ n | n == eobcode -> return acc+ n | n == litcode -> decodeIt' $ acc |> (fromIntegral $ value entry)+ n | n > litcode -> error "Sonderfall not handled"+ _ -> do+ -- n <- (+ value entry) <$> getAndConsume (numExtraBits entry - 16)+ n <- (+ value entry) <$> getAndConsume (numExtraBits entry)+ distEntry <- readEntryRaw dt+ dist <- (+ value distEntry) <$> getAndConsume (numExtraBits distEntry)+ let new = DS.drop (length acc - dist) acc+ new' = foldl (\a _ -> a >< new) empty [0..m]+ m = n `div` dist+ l = (acc >< (DS.take n new'))+ decodeIt' l+ ++-- |Decompress one or more lzh compressed blocks+decompressBlock :: BS.ByteString -> BS.ByteString+decompressBlock inp = blocks+ where+ blocks = evalState decompressor . makeStream $ inp++skipNonsenseBits :: State BitStream ()+skipNonsenseBits = do+ numNonsenseBits <- getAndConsume 2+ when (numNonsenseBits > 0) $+ void $ getAndConsume numNonsenseBits++decompressor :: State BitStream BS.ByteString+decompressor = skipNonsenseBits >> (BS.pack . toList <$> decompressor' empty)++decompressor' :: DS.Seq Word8 -> State BitStream (DS.Seq Word8)+decompressor' acc = do+ lastBlock <- getAndConsume 1+ blockType <- getAndConsume 2+ res <- case blockType of+ 1 -> decompressStaticBlock acc+ 2 -> decompressDynamicBlock acc+ _ -> error $ "Block type " ++ show blockType ++ " not supported!"+ case lastBlock of+ 1 -> return res+ 0 -> decompressor' res++decompressDynamicBlock :: DS.Seq Word8 -> State BitStream (DS.Seq Word8)+decompressDynamicBlock acc = do+ numLiterals <- (+ 257) <$> getAndConsume 5+ numDistanceCodes <- (+ 1) <$> getAndConsume 5+ numBitLengths <- (+ 4) <$> getAndConsume 4+ let bitLengthPositions = Prelude.take numBitLengths border+ bitLengths' <- mapM (\blp -> (,) blp <$> getAndConsume 3) bitLengthPositions+ let bitLengths = makeFlexList (0, 18) 0 bitLengths'+ huft = makeHuffmanTree bitLengths 19 [] []+ entriesToRead = numLiterals + numDistanceCodes+ ll <- entryReader [] huft entriesToRead (-1)+ let lengthCodes = take numLiterals ll+ distCodes = take numDistanceCodes $ drop numLiterals ll+ lengthTree = makeHuffmanTree lengthCodes 257 cplens csExtraLenBits+ distTree = makeHuffmanTree distCodes 0 cpdist csExtraDistBits+ decodeIt lengthTree distTree acc++decompressStaticBlock :: DS.Seq Word8 -> State BitStream (DS.Seq Word8)+decompressStaticBlock acc = do+ -- Length and dist codes copied from vpa108csulzh.cpp under GPL by SAP AG+ let lengthCodes = replicate 144 8 ++ replicate 112 9 ++ replicate 24 7 ++ replicate 8 8+ distCodes = replicate 30 5+ -- End length and dist codes copied from vpa108csulzh.cpp under GPL by SAP AG+ let lengthTree = makeHuffmanTree lengthCodes 257 cplens csExtraLenBits+ distTree = makeHuffmanTree distCodes 0 cpdist csExtraDistBits+ decodeIt lengthTree distTree acc
+ src/Codec/Archive/SAPCAR/FlexibleUtils.hs view
@@ -0,0 +1,48 @@+-- |+-- Module: FlexibleUtils+-- Copyright: (C) 2015-2016, Virtual Forge GmbH+-- License: GPL2+-- Maintainer: Hans-Christian Esperer <hc@hcesperer.org>+-- Stability: experimental+-- Portability: portable+-- |+-- (De-)compress SAPCAR files+--+-- Copyright (C) 2016, Virtual Forge GmbH+--+-- This program is free software; you can redistribute it and/or modify+-- it under the terms of the GNU General Public License as published by+-- the Free Software Foundation; either version 2 of the License, or (at+-- your option) any later version.+--+-- This program is distributed in the hope that it will be useful, but+-- WITHOUT ANY WARRANTY; without even the implied warranty of+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU+-- General Public License for more details.+--+-- You should have received a copy of the GNU General Public License+-- along with this program; if not, write to the Free Software+-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307+-- USA+module Codec.Archive.SAPCAR.FlexibleUtils+ ( makeFlexArray+ , makeFlexList+ ) where++import Control.Monad.ST+import qualified Data.Array.ST as FLEX+import GHC.Arr++-- |Make an array based on a range, a default value and a list of+-- tuples that can be used to initialise specific entries of the+-- array.+makeFlexArray :: (Int, Int) -> a -> [(Int, a)] -> GHC.Arr.Array Int a+makeFlexArray arange defval pairs = FLEX.runSTArray $ do+ bl <- FLEX.newArray arange defval -- :: ST s (FLEX.STArray s Int a)+ mapM_ (uncurry $ FLEX.writeArray bl) pairs+ return bl++-- |Make a flexible array and convert it to a list using the+-- natural order of the array.+makeFlexList :: (Int, Int) -> Int -> [(Int, Int)] -> [Int]+makeFlexList a b c = elems $ makeFlexArray a b c
+ test/Spec.hs view
@@ -0,0 +1,37 @@+{-# LANGUAGE OverloadedStrings #-}++import Control.Monad+import Crypto.Hash.SHA256+import Data.Conduit+import Data.Hex+import Path+import System.IO++import qualified Data.ByteString as S++import SAPCAR++bufSink :: Sink S.ByteString IO S.ByteString+bufSink = S.concat . reverse <$> bufSink' []+ where+ bufSink' :: [S.ByteString] -> Sink S.ByteString IO [S.ByteString]+ bufSink' acc = do+ chunk <- await+ case chunk of+ Just chunk' -> bufSink' (chunk':acc)+ Nothing -> return acc++main :: IO ()+main = do+ path <- parseRelFile "test/test6.sar"+ res <- withSapCarPath path $ do+ entries <- getEntries+ unless (length entries == 1) $ error "test6.sar should contain exactly one entry!"+ let entry = entries !! 0+ unless (cfFileName entry == "pg244.txt") $ error "Entry in test6.sar should be called 'pg244.txt'!"+ unless (cfFileType entry == CarFile) $ error "Entry in test6.sar should be of type 'file'!"+ sourceEntry entry bufSink++ let correctDigest = "B9A995A6C7A9E75326CE524CA14D4DC7959F012A9E81BF0A5CD0E709767EDB63"+ unless (correctDigest == hex (hash res)) $ error "Wrong sha256 hash for pg244.txt"+