Source

hs-libzip / LibZip / Codec / Archive / LibZip.hs

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
{- | Monadic interface to @libzip@.

Most of the operations on zip archive happen within 'Archive' monad
(see 'withArchive').
Partial reading of the files in the archive may be performed from
within 'Entry' monad (see 'fromFile').
Both 'Archive' and 'Entry' are monad transformers over 'IO', and allow
for IO with single and double 'lift'ing respectingly.

Note: LibZip does not handle text encodings. Even if its API accepts
'String's (e.g. in 'sourceBuffer'), character codes above 255 should
not be used.  The user is responsible of proper encoding the text
data.

/Examples/

List files in the zip archive:

@
import System.Environment (getArgs)
import Codec.Archive.LibZip

main = do
  (zipfile:_) <- getArgs
  files <- withArchive [] zipfile $ fileNames []
  mapM_ putStrLn files
@

Create a zip archive and a add file to the archive:

@
import System.Environment (getArgs)
import Codec.Archive.LibZip

main = do
  (zipfile:_) <- getArgs
  withArchive [CreateFlag] zipfile $ do
     zs <- sourceBuffer \"Hello World!\"
     addFile \"hello.txt\" zs
@

Extract and print a file from the zip archive:

@
import System.Environment (getArgs)
import Codec.Archive.LibZip

main = do
  (zipfile:file:_) <- getArgs
  bytes <- withArchive [] zipfile $ fileContents [] file
  putStrLn bytes
@

See also an implementation of a simple zip archiver @hzip.hs@ in the
@examples/@ directory of the source distribution.

-}
module Codec.Archive.LibZip
    (
    -- * Types
      Archive
    , Entry
    , ZipStat(..)
    -- * Archive operations
    , withArchive, getZip
    , numFiles, fileName, nameLocate, fileNames
    , fileSize, fileSizeIx
    , fileStat, fileStatIx
    , deleteFile, deleteFileIx
    , renameFile, renameFileIx
    , addFile, addDirectory
    , replaceFile, replaceFileIx
    , sourceBuffer, sourceFile, sourceZip
    , PureSource(..), sourcePure
    , getComment, setComment, removeComment
    , getFileComment, getFileCommentIx
    , setFileComment, setFileCommentIx
    , removeFileComment, removeFileCommentIx
    , unchangeFile, unchangeFileIx
    , unchangeArchive, unchangeAll
    -- * File reading operations
    , fromFile, fromFileIx
    , readBytes, skipBytes, readContents
    , fileContents, fileContentsIx
    -- * Flags and options
    , OpenFlag(..)
    , FileFlag(..)
    , ZipCompMethod(..)
    , ZipEncryptionMethod(..)
    -- * Exception handling
    , ZipError(..)
    , catchZipError
    -- * Re-exports
    , lift
    ) where

import Bindings.LibZip
import Codec.Archive.LibZip.Types
import Codec.Archive.LibZip.Errors

import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Data.Word (Word8)
import Control.Monad (when)
import Control.Monad.State.Strict
    (StateT(..), MonadState(..), MonadTrans(..), lift, liftM)
import Foreign.C.Error (Errno(..), eINVAL)
import Foreign.C.String (withCString, withCStringLen, peekCString)
import Foreign.C.Types (CInt, CULLong)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Array (allocaArray, peekArray, withArrayLen, pokeArray)
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr, nullPtr, castPtr)
import Foreign.Storable (Storable, peek, poke, pokeElemOff, sizeOf)
import qualified Control.Exception as E

--
-- Types
--

-- | Monadic computation with a zip archive. See 'withArchive'.
type Archive a = StateT Zip IO a

-- | Monadic computation to read from open archive entries.
-- See 'fromFile' and 'fromFileIx'.
type Entry a = StateT
    (ZipFile,Integer,[FileFlag])   -- (file, position index, access flags)
    (StateT Zip IO)                -- archive monad
    a

--
-- Archive operations
--

-- | Top-level wrapper for operations with an open
-- archive. 'withArchive' opens and closes the file
-- automatically. On error it throws 'ZipError'.
withArchive :: [OpenFlag]  -- ^ Checks for consistency or existence.
            -> FilePath    -- ^ Filename of the zip archive.
            -> Archive a   -- ^ Action to do with the archive.
            -> IO a
withArchive flags path action =
  withCString path $ \path' ->
  alloca $ \errp ->
  c'zip_open path' (combine flags) errp >>= \z ->
  if z == nullPtr
    then peek errp >>= E.throwIO. errFromCInt
    else do
      r <- fst `liftM` runStateT action z
      e <- c'zip_close z
      if e /= 0
        then get_error z >>= E.throwIO
        else return r

-- | Get the number of entries in the archive.
numFiles :: [FileFlag] -> Archive Integer
numFiles flags  = do
  z <- getZip
  lift $ fromIntegral `liftM` c'zip_get_num_entries z (combine flags)

-- | Get name of an entry in the archive by its index.
fileName :: [FileFlag]  -- ^ 'FileUNCHANGED' flag can be used.
         -> Integer     -- ^ Position index of a file in the archive.
         -> Archive FilePath  -- ^ Name of the file in the archive.
fileName flags i = do
  z <- getZip
  lift $ do
    n <- c'zip_get_name z (fromIntegral i) (combine flags)
    doIf' (n /= nullPtr) z $ peekCString n

-- | Locate an entry (get its index) in the archive by its name.
nameLocate :: [FileFlag]  -- ^ Filename lookup mode.
           -> FilePath    -- ^ Name of the file in the archive.
           -> Archive (Maybe Integer)  -- ^ 'Just' position index if found.
nameLocate flags name = do
  z <- getZip
  lift $
    withCString name $ \name' -> do
    i <- fromIntegral `liftM` c'zip_name_locate z name' (combine flags)
    if i < 0
       then return Nothing
       else return (Just i)

-- | Get names of all entries (files and directories) in the archive.
fileNames :: [FileFlag]  -- ^ 'FileUNCHANGED' flag is accepted.
          -> Archive [FilePath]
fileNames flags = do
  n <- numFiles flags
  mapM (fileName flags) [0..n-1]

-- | Get size of a file in the archive.
fileSize :: [FileFlag]  -- ^ Filename lookup mode, 'FileUNCHANGED' can be used.
         -> FilePath    -- ^ Name of the file in the archive.
         -> Archive Integer -- ^ File size.
fileSize flags name = fileStat flags name >>= return . zs'size

-- | Get size of a file in the archive (by index).
fileSizeIx :: [FileFlag]  -- ^ 'FileUNCHANGED' is accepted.
           -> Integer     -- ^ Position index of a file in the archive.
           -> Archive Integer -- ^ File size.
fileSizeIx flags i = fileStatIx flags i >>= return . zs'size

-- | Get information about a file in the archive.
fileStat :: [FileFlag]  -- ^ Filename lookup mode, 'FileUNCHANGED' can be used.
         -> FilePath    -- ^ Name of the file in the archive.
         -> Archive ZipStat  -- ^ Infomation about the file.
fileStat flags name = do
  z <- getZip
  lift $
       withCString name $ \name' ->
       alloca $ \stat -> do
       c'zip_stat_init stat
       r <- c'zip_stat z name' (combine flags) stat
       doIf' (r == 0) z $ toZipStat =<< peek stat

-- | Get information about a file in the archive (by index).
fileStatIx :: [FileFlag]  -- ^ 'FileUNCHANGED' can be used.
           -> Integer     -- ^ Position index of a file in the archive.
           -> Archive ZipStat  -- ^ Information about the file.
fileStatIx flags i = do
  z <- getZip
  lift $
       alloca $ \stat -> do
       r <- c'zip_stat_index z (fromIntegral i) (combine flags) stat
       doIf' (r == 0) z $ toZipStat =<< peek stat

-- | Delete file from the archive.
deleteFile :: [FileFlag]  -- ^ Filename lookup mode.
           -> FilePath    -- ^ Filename.
           -> Archive ()
deleteFile flags name = do
  mbi <- nameLocate flags name
  maybe (lift $ E.throwIO ErrNOENT) deleteFileIx mbi

-- | Delete file (referenced by position index) from the archive.
deleteFileIx :: Integer  -- ^ Position index of a file in the archive.
             -> Archive ()
deleteFileIx i = do
  z <- getZip
  r <- lift $ c'zip_delete z (fromIntegral i)
  if r == 0
     then return ()
     else lift $ get_error z >>= E.throwIO

-- | Rename file in the archive.
renameFile :: [FileFlag]  -- ^ Filename lookup mode.
           -> FilePath    -- ^ Old name.
           -> FilePath    -- ^ New name.
           -> Archive ()
renameFile flags oldname newname = do
  mbi <- nameLocate flags oldname
  maybe (lift $ E.throwIO ErrNOENT) (\i -> renameFileIx i newname) mbi

-- | Rename file (referenced by position index) in the archive.
renameFileIx :: Integer  -- ^ Position index of a file in the archive.
             -> FilePath -- ^ New name.
             -> Archive ()
renameFileIx i newname = do
  z <- getZip
  r <- lift $ withCString newname $ c'zip_rename z (fromIntegral i)
  if r == 0
     then return ()
     else lift $ get_error z >>= E.throwIO

-- | Add a file to the archive.
addFile :: FilePath   -- ^ Name of the file to create.
        -> ZipSource  -- ^ Source where file data is obtained from.
        -> Archive Int  -- ^ Position index of the new file.
addFile name src = do
  z <- getZip
  lift $ withCString name $ \name' -> do
    i <- c'zip_add z name' src
    if i < 0
       then c'zip_source_free src >> get_error z >>= E.throwIO
       else return $ fromIntegral i

-- | Add a directory to the archive.
addDirectory :: FilePath     -- ^ Directory's name in the archive.
             -> Archive Int  -- ^ Position index of the new directory entry.
addDirectory name = do
  z <- getZip
  r <- lift $ withCString name $ c'zip_add_dir z
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return (fromIntegral r)

-- | Replace a file in the archive.
replaceFile :: [FileFlag]  -- ^ Filename lookup mode.
            -> FilePath    -- ^ File to replace.
            -> ZipSource   -- ^ Source where the new file data is obtained from.
            -> Archive ()
replaceFile flags name src = do
  mbi <- nameLocate flags name
  maybe (lift $ c'zip_source_free src >> E.throwIO ErrNOENT)
        (\i -> replaceFileIx i src >> return ()) mbi

-- | Replace a file in the archive (referenced by position index).
replaceFileIx :: Integer   -- ^ Position index of a file in the archive.
              -> ZipSource -- ^ Source where the new file data is obtained from
              -> Archive ()
replaceFileIx i src = do
  z <- getZip
  lift $ do
    r <- c'zip_replace z (fromIntegral i) src
    if r < 0
       then c'zip_source_free src >> get_error z >>= E.throwIO
       else return ()

-- | Create a data source. Note: input is converted to @[Word8]@ internally.
sourceBuffer :: (Enum a)
             => [a]
             -> Archive ZipSource
sourceBuffer src = do
  let ws = map (toEnum . fromEnum) src :: [Word8]
  z <- getZip
  lift $ withArrayLen ws $ \len buf -> do
      zs <- c'zip_source_buffer z (castPtr buf) (fromIntegral len) 0
      if zs == nullPtr
         then get_error z >>= E.throwIO
         else return zs

-- | Create a data source from a file.
sourceFile :: FilePath   -- ^ File to open.
           -> Integer    -- ^ Offset from the beginning of the file.
           -> Integer    -- ^ The number of bytes to read. If @0@ or @-1@,
                         -- the read till the end of file.
           -> Archive ZipSource
sourceFile name offset len = do
  z <- getZip
  lift $ withCString name $ \name' -> do
      zs <- c'zip_source_file z name' (fromIntegral offset) (fromIntegral len)
      if zs == nullPtr
         then get_error z >>= E.throwIO
         else return zs

-- | Create a data source from a file in the zip archive.
sourceZip :: [FileFlag]  -- ^ 'FileUNCHANGED' and 'FileRECOMPRESS' can be used.
          -> Zip         -- ^ Source archive.
          -> Integer     -- ^ Position index of a file in the source archive.
          -> Integer     -- ^ Offset from the beginning of the file.
          -> Integer     -- ^ The number of bytes to read. If @0@ or @-1@,
                         -- then read till the end of file.
          -> Archive ZipSource
sourceZip flags srcz srcidx offset len = do
  z <- getZip
  lift $ do
    zs <- c'zip_source_zip z srcz (fromIntegral srcidx)
          (combine flags) (fromIntegral offset) (fromIntegral len)
    if zs == nullPtr
       then get_error z >>= E.throwIO
       else return zs

-- | Create a data source from a 'PureSource'.
-- Note: input of @[a]@ is converted to @[Word8]@ internally.
sourcePure :: (Enum a, Storable a, Storable st, Integral szt)
           => PureSource a st szt -> Archive ZipSource
sourcePure pureSrc = do
  z <- getZip
  lift $ do
    cb <- mk'zip_source_callback (runPureSource pureSrc)
    zs <- with (srcState pureSrc) $
          \pState -> c'zip_source_function z cb (castPtr pState)
    if zs == nullPtr
       then get_error z >>= E.throwIO
       else return zs

-- | Wrapper for a user-provided pure function to be used with 'sourcePure'.
-- Data size should be known in advance ('srcSize').
-- The function should support reading by chunks ('readSrc').
data PureSource a st szt = PureSource {
    srcState :: st     -- ^ Initial state of the source.
  , srcSize  :: szt    -- ^ Total size of the data.
  , srcMTime :: Maybe UTCTime
                -- ^ Modification time (current time if Nothing).
  , readSrc  :: szt -> st -> Maybe (szt, [a], st)
                -- ^ Read a chunk of the data, return @Just@ the size
                -- of data read, the data themselves and the new state
                -- of the source, or @Nothing@ on error.
  }

runPureSource :: (Enum a, Storable a, Storable st, Integral szt) =>
       PureSource a st szt
    -> (Ptr () -> Ptr () -> CULLong -> C'zip_source_cmd -> IO CULLong)
runPureSource src pState pData len cmd
  | cmd == c'ZIP_SOURCE_OPEN = return 0
  | cmd == c'ZIP_SOURCE_READ = do
      s <- peek (castPtr pState :: Ptr st)
      case readSrc (src { srcState = s }) (fromIntegral len) s of
        Just (len',bs,s') -> do
          pokeArray (castPtr pData :: Ptr Word8) (map (toEnum.fromEnum) bs)
          poke (castPtr pState) s'
          return (fromIntegral len')
        Nothing -> return (-1)
  | cmd == c'ZIP_SOURCE_CLOSE = return 0
  | cmd == c'ZIP_SOURCE_STAT = do
      t <- maybe getCurrentTime return (srcMTime src)
      let pt = fromInteger . round . utcTimeToPOSIXSeconds $ t
      let pStat = castPtr pData
      c'zip_stat_init pStat
      stat <- peek pStat
      let stat' = stat { c'zip_stat'mtime = pt
                       , c'zip_stat'size = fromIntegral $ srcSize src }
      poke pStat stat'
      return $ fromIntegral (sizeOf stat')
  | cmd == c'ZIP_SOURCE_ERROR = do
      let pErrs = castPtr pData :: Ptr CInt
      poke pErrs (fromIntegral . fromEnum $ ErrINVAL)
      let (Errno esys) = eINVAL
      pokeElemOff pErrs 1 esys
      return $ fromIntegral (2 * sizeOf esys)
  | cmd == c'ZIP_SOURCE_FREE = return 0
  | otherwise = return (-1)

-- | Get zip archive comment.
getComment :: [FileFlag]  -- ^ 'FileUNCHANGED' can be used.
           -> Archive (Maybe String)
getComment flags = do
  z <- getZip
  (c,n) <- lift $ alloca $ \lenp -> do
         c <- c'zip_get_archive_comment z lenp (combine flags)
         n <- peek lenp
         return (c,n)
  if  c == nullPtr
    then return Nothing
    else lift $ peekCString c >>= return . Just . take (fromIntegral n)

-- | Set zip archive comment.
setComment :: String   -- ^ Comment message.
           -> Archive ()
setComment msg = do
  z <- getZip
  r <- lift $ withCStringLen msg $ \(msg',i') ->
       c'zip_set_archive_comment z msg' (fromIntegral i')
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Remove zip archive comment.
removeComment :: Archive ()
removeComment = do
  z <- getZip
  r <- lift $ c'zip_set_archive_comment z nullPtr 0
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Get comment for a file in the archive.
getFileComment :: [FileFlag]  -- ^ Filename lookup mode.
               -> FilePath    -- ^ Filename
               -> Archive (Maybe String)
getFileComment flags name = do
  mbi <- nameLocate flags name
  maybe (lift $ E.throwIO ErrNOENT) (getFileCommentIx flags) mbi

-- | Get comment for a file in the archive (referenced by position index).
getFileCommentIx :: [FileFlag]  -- ^ FileUNCHANGED can be used.
                 -> Integer     -- ^ Position index of the file.
                 -> Archive (Maybe String)
getFileCommentIx flags i = do
  z <- getZip
  (c,n) <- lift $ alloca $ \lenp -> do
           c <- c'zip_get_file_comment z (fromIntegral i) lenp (combine flags)
           n <- peek lenp
           return (c,n)
  if c == nullPtr
     then return Nothing
     else lift $ peekCString c >>= return . Just . take (fromIntegral n)

-- | Set comment for a file in the archive.
setFileComment :: [FileFlag]   -- ^ Name lookup mode.
               -> FilePath     -- ^ Filename.
               -> String       -- ^ New file comment.
               -> Archive ()
setFileComment flags path comment = do
  mbi <- nameLocate flags path
  maybe (lift $ E.throwIO ErrNOENT) (flip setFileCommentIx comment) mbi

-- | Set comment for a file in the archive (referenced by position index).
setFileCommentIx :: Integer    -- ^ Position index of a file in the archive.
                 -> String     -- ^ New file comment.
                 -> Archive ()
setFileCommentIx i comment = do
  z <- getZip
  r <- lift $ withCStringLen comment $ \(msg,len) ->
       c'zip_set_file_comment z (fromIntegral i) msg (fromIntegral len)
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Remove comment for a file in the archive.
removeFileComment :: [FileFlag]  -- ^ Filename lookup mode.
                  -> FilePath    -- ^ Filename.
                  -> Archive ()
removeFileComment flags path = do
  mbi <- nameLocate flags path
  maybe (lift $ E.throwIO ErrNOENT) removeFileCommentIx mbi

-- | Remove comment for a file in the archive (referenced by position index).
removeFileCommentIx :: Integer -- ^ Position index of a file in the archive.
                    -> Archive ()
removeFileCommentIx i = do
  z <- getZip
  r <- lift $ c'zip_set_file_comment z (fromIntegral i) nullPtr 0
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Undo changes to a file in the archive.
unchangeFile :: [FileFlag]  -- ^ Filename lookup mode.
             -> FilePath    -- ^ Filename.
             -> Archive ()
unchangeFile flags name = do
  mbi <- nameLocate flags name
  maybe (lift $ E.throw ErrNOENT) unchangeFileIx mbi

-- | Undo changes to a file in the archive (referenced by position index).
unchangeFileIx :: Integer  -- ^ Position index of a file in the archive.
               -> Archive ()
unchangeFileIx i = do
  z <- getZip
  lift $ do
    r <- c'zip_unchange z (fromIntegral i)
    if r < 0
       then get_error z >>= E.throwIO
       else return ()

-- | Undo global changes to zip archive (revert changes to the archive
-- comment and global flags).
unchangeArchive :: Archive ()
unchangeArchive = do
  z <- getZip
  lift $ do
    r <- c'zip_unchange_archive z
    if r < 0
       then get_error z >>= E.throwIO
       else return ()

-- | Undo all changes in a zip archive.
unchangeAll :: Archive ()
unchangeAll = do
  z <- getZip
  lift $ do
    r <- c'zip_unchange_all z
    if r < 0
       then get_error z >>= E.throwIO
       else return ()

--
-- File reading operations
--

-- | Wrapper for operations with a file in the archive. 'fromFile' is normally
-- called from within an 'Archive' action (see also 'withArchive').
-- 'fromFile' can be replaced with 'fileContents' to read an entire file at
-- once.
fromFile :: [FileFlag]  -- ^ Filename lookup mode,
                        -- 'FileCOMPRESSED' and 'FileUNCHANGED' can be used.
         -> FilePath    -- ^ Name of the file in the arhive.
         -> Entry a     -- ^ Action with the file.
         -> Archive a
fromFile flags name action = do
    z <- getZip
    nameLocate flags name >>= maybe (lift $ get_error z >>= E.throwIO) runAction
  where
    runAction i = do
      z <- getZip
      zf <- lift $ withCString name $ \n -> c'zip_fopen z n (combine flags)
      if zf == nullPtr
        then lift $ get_error z >>= E.throwIO
        else do
          r <- fst `liftM` runStateT action (zf,i,flags)
          e <- lift $ c'zip_fclose zf
          if e /= 0
            then lift $ E.throwIO $ (toEnum . fromIntegral $ e :: ZipError)
            else return r

-- | Wrapper for operations with a file in the archive. File is referenced
-- by index (position). 'fromFileIx' is normally called from within
-- an 'Archive' action (see also 'withArchive'). 'fromFileIx' can be replaced
-- with 'fileContentsIx' to read an entire file at once.
fromFileIx :: [FileFlag] -- ^ 'FileCOMPRESSED' and 'FileUNCHANGED' can be used.
           -> Integer    -- ^ Position index of a file in the archive.
           -> Entry a    -- ^ Action with the file.
           -> Archive a
fromFileIx flags i action = do
  z <- getZip
  zf <- lift $ c'zip_fopen_index z (fromIntegral i) (combine flags)
  if zf == nullPtr
     then lift $ get_error z >>= E.throwIO
     else do
       r <- fst `liftM` runStateT action (zf,i,flags)
       e <- lift $ c'zip_fclose zf
       if e /= 0
          then lift $ E.throwIO $ (toEnum . fromIntegral $ e :: ZipError)
          else return r

-- | Read at most @n@ bytes from the file.
readBytes ::
    (Enum a)
    => Integer   -- ^ The number of bytes to read.
    -> Entry [a] -- ^ Bytes read.
readBytes n = do
  lift . lift $
    when (n > toInteger (maxBound::Int))
      (E.throwIO ErrMEMORY) -- allocaArray can't allocate > (maxBound::Int)
  (zf,_,_) <- get
  lift . lift $ allocaArray (fromIntegral n) $ \buf -> do
         nread <- c'zip_fread zf (castPtr buf) (fromIntegral n)
         if nread < 0
            then
              get_file_error zf >>= E.throwIO
            else do
              bs <- peekArray (fromIntegral nread) buf :: IO [Word8]
              return . map (toEnum . fromEnum) $ bs

-- | Skip @n@ bytes from the open file. Note: this is not faster than reading.
skipBytes :: Integer -> Entry ()
skipBytes n = (readBytes n :: Entry [Word8]) >> return ()

-- | Read entire file contents.
readContents ::
    (Enum a)
    => Entry [a]  -- ^ Contents of the file.
readContents = do
  (_,i,flags) <- get
  sz <- lift $ fileSizeIx flags i
  readBytes sz

-- | Read entire file. Shortcut for 'readContents' from within 'Archive' monad.
fileContents :: (Enum a)
    => [FileFlag]
    -> FilePath
    -> Archive [a]
fileContents flags name = fromFile flags name readContents

-- | Read entire file (referenced by position index). Shortcut for
-- 'readContents' from within 'Archive' monad.
fileContentsIx :: (Enum a)
    => [FileFlag]
    -> Integer
    -> Archive [a]
fileContentsIx flags i = fromFileIx flags i readContents

--
-- Helpers
--

-- | Get archive handler. Throw 'ErrINVAL' if the archive is closed.
getZip :: Archive Zip
getZip = do
  z <- get
  if z == nullPtr
     then lift $ E.throwIO ErrINVAL
     else return z

-- | Get and throw a 'ZipError' if condition fails. Otherwise work normally.
doIf :: Bool -> Zip -> (Zip -> IO a) -> IO a
doIf cnd z action =
    if cnd
       then action z
       else get_error z >>= E.throwIO

-- | Get and throw a 'ZipError' if condition fails. See also 'doIf'.
doIf' :: Bool -> Zip -> (IO a) -> IO a
doIf' cnd z action = doIf cnd z (const action)