packages feed

ntfs 0.1.0.1 → 0.1.0.2

raw patch · 9 files changed

+340/−12 lines, 9 filesPVP: minor bump suggested

API additions: PVP suggests at least a minor version bump

API changes (from Hackage documentation)

+ NTFS.File: FileEntry :: Word32 -> Word16 -> [FileName] -> Maybe StandardInformation -> [(Maybe ByteString, FileData)] -> FileEntry
+ NTFS.File: [entryData] :: FileEntry -> [(Maybe ByteString, FileData)]
+ NTFS.File: [entryFileNames] :: FileEntry -> [FileName]
+ NTFS.File: [entryRecordFlags] :: FileEntry -> Word16
+ NTFS.File: [entryRecordNumber] :: FileEntry -> Word32
+ NTFS.File: [entryStandardInformation] :: FileEntry -> Maybe StandardInformation
+ NTFS.File: data FileEntry
+ NTFS.File: instance GHC.Classes.Eq NTFS.File.FileEntry
+ NTFS.File: instance GHC.Internal.Show.Show NTFS.File.FileEntry
+ NTFS.File: isEntryDirectory :: FileEntry -> Bool
+ NTFS.File: isEntryInUse :: FileEntry -> Bool
+ NTFS.File: parseFileEntry :: MFTRecord -> Either ParseError FileEntry
+ NTFS.MFT: mftRecordCount :: Volume -> IO (Either ParseError Int)
+ NTFS.MFT: readAllMFTRecords :: Volume -> IO (Either ParseError [MFTRecord])
+ NTFS.Volume: readData :: Volume -> FileData -> IO (Either ParseError ByteString)

Files

CHANGELOG.md view
@@ -8,6 +8,18 @@  ## [Unreleased] +## [0.1.0.2] - 2026-11-27++### Added++- `NTFS.File` with a combined view of the attributes of one MFT record.+- `NTFS.Volume.readData` for resident and non-resident attribute bytes, including sparse runs.+- `NTFS.MFT` with MFT record counts and ordered record enumeration.++### Fixed++- Accept short `$STANDARD_INFORMATION` values used by system files.+ ## [0.1.0.1] - 2026-11-27  ### Added
README.md view
@@ -6,8 +6,19 @@  ## Status -Early development. The boot sector parser and volume-level MFT record reads-are available so far.+The volume, MFT and attribute layers are implemented, along with a combined+file view:++- `NTFS.BootSector` and `NTFS.Volume` for geometry, MFT reads and data reads.+- `NTFS.MFT.Record`, `NTFS.MFT.Attribute` and `NTFS.MFT` for records,+  attribute headers and MFT enumeration.+- `NTFS.Runlist` for mapping pairs and sparse runs.+- `NTFS.Attribute.Data`, `NTFS.Attribute.StandardInformation` and+  `NTFS.Attribute.FileName` for common attribute values.+- `NTFS.File` for the metadata and data of one record.++Directory index parsing and path lookup are not available yet.+The current Hackage release is `0.1.0.2`.  ## Building 
ntfs.cabal view
@@ -1,10 +1,10 @@ cabal-version:      2.4 name:               ntfs-version:            0.1.0.1+version:            0.1.0.2 synopsis:           Pure Haskell library for reading NTFS disk images description:-  Low-level parsers for NTFS volume geometry, MFT records, attributes and-  runlists, with a high-level file system API built on top.+  Parsers for NTFS volume geometry, MFT records, attributes and runlists, with+  MFT enumeration, data reads and a combined view of file metadata.  license:            BSD-3-Clause license-file:       LICENSE@@ -27,6 +27,8 @@                       NTFS.Attribute.FileName                       NTFS.Attribute.StandardInformation                       NTFS.BootSector+                      NTFS.File+                      NTFS.MFT                       NTFS.MFT.Attribute                       NTFS.MFT.Record                       NTFS.Runlist
src/NTFS.hs view
@@ -5,6 +5,8 @@   , module NTFS.Attribute.FileName   , module NTFS.Attribute.StandardInformation   , module NTFS.BootSector+  , module NTFS.File+  , module NTFS.MFT   , module NTFS.MFT.Attribute   , module NTFS.MFT.Record   , module NTFS.Runlist@@ -15,6 +17,8 @@ import           NTFS.Attribute.FileName import           NTFS.Attribute.StandardInformation import           NTFS.BootSector+import           NTFS.File+import           NTFS.MFT import           NTFS.MFT.Attribute import           NTFS.MFT.Record import           NTFS.Runlist
src/NTFS/Attribute/StandardInformation.hs view
@@ -13,6 +13,7 @@  -- | Metadata shared by all file names of a record. -- Timestamps are Windows @FILETIME@ values (100 ns since 1601-01-01).+-- Fields absent from short (48-byte) values are reported as zero. data StandardInformation = StandardInformation   { standardCreationTime   :: Word64   , standardFileAlterTime  :: Word64@@ -38,7 +39,7 @@         NonResidentValue{} ->           Left (InvalidValue "$STANDARD_INFORMATION is not resident")         ResidentValue bytes-          | BS.length bytes < 0x48 ->+          | BS.length bytes < 0x30 ->               Left (UnexpectedEndOfData "$STANDARD_INFORMATION value is truncated")           | otherwise ->               Right@@ -51,11 +52,21 @@                   , standardMaxVersion = word32At bytes 0x24                   , standardVersion = word32At bytes 0x28                   , standardClassId = word32At bytes 0x2c-                  , standardOwnerId = word32At bytes 0x30-                  , standardSecurityId = word32At bytes 0x34-                  , standardQuotaCharged = word64At bytes 0x38-                  , standardUpdateSequence = word64At bytes 0x40+                  , standardOwnerId = optionalWord32 bytes 0x30+                  , standardSecurityId = optionalWord32 bytes 0x34+                  , standardQuotaCharged = optionalWord64 bytes 0x38+                  , standardUpdateSequence = optionalWord64 bytes 0x40                   }++optionalWord32 :: BS.ByteString -> Int -> Word32+optionalWord32 bytes offset+  | offset + 4 <= BS.length bytes = word32At bytes offset+  | otherwise = 0++optionalWord64 :: BS.ByteString -> Int -> Word64+optionalWord64 bytes offset+  | offset + 8 <= BS.length bytes = word64At bytes offset+  | otherwise = 0  word32At :: BS.ByteString -> Int -> Word32 word32At bytes offset =
+ src/NTFS/File.hs view
@@ -0,0 +1,61 @@+-- | High-level combination of the attributes of one MFT record.+module NTFS.File+  ( FileEntry (..)+  , isEntryInUse+  , isEntryDirectory+  , parseFileEntry+  ) where++import           Data.Bits                          ((.&.))+import qualified Data.ByteString                    as BS+import           Data.Word                          (Word16, Word32)++import           NTFS.Attribute.Data+import           NTFS.Attribute.FileName+import           NTFS.Attribute.StandardInformation+import           NTFS.MFT.Attribute+import           NTFS.MFT.Record+import           NTFS.Types                         (ParseError (..))++-- | Metadata and data found in one MFT record.+data FileEntry = FileEntry+  { entryRecordNumber        :: Word32+  , entryRecordFlags         :: Word16+  , entryFileNames           :: [FileName]+  , entryStandardInformation :: Maybe StandardInformation+  , entryData                :: [(Maybe BS.ByteString, FileData)]+  } deriving (Eq, Show)++-- | Whether the underlying record is marked as in use.+isEntryInUse :: FileEntry -> Bool+isEntryInUse entry = entryRecordFlags entry .&. 0x0001 /= 0++-- | Whether the underlying record describes a directory.+isEntryDirectory :: FileEntry -> Bool+isEntryDirectory entry = entryRecordFlags entry .&. 0x0002 /= 0++-- | Combine the known attributes of a record. Unknown attributes are ignored.+parseFileEntry :: MFTRecord -> Either ParseError FileEntry+parseFileEntry record = do+  attributes <- mapM parseAttribute relevant+  names <- mapM parseFileName (matching attributeTypeFileName attributes)+  information <- mapM parseStandardInformation (matching attributeTypeStandardInformation attributes)+  dataAttributes <- mapM parseDataAttribute (matching attributeTypeData attributes)+  pure+    FileEntry+      { entryRecordNumber = recordNumber record+      , entryRecordFlags = recordFlags record+      , entryFileNames = names+      , entryStandardInformation = case information of+          value:_ -> Just value+          []      -> Nothing+      , entryData = zip (map attributeName (matching attributeTypeData attributes)) dataAttributes+      }+  where+    relevant = filter (\raw -> rawAttributeType raw `elem` knownTypes) (recordAttributes record)+    knownTypes =+      [ attributeTypeStandardInformation+      , attributeTypeFileName+      , attributeTypeData+      ]+    matching typeCode = filter ((== typeCode) . attributeTypeCode)
+ src/NTFS/MFT.hs view
@@ -0,0 +1,55 @@+-- | Enumeration of MFT records in a volume.+module NTFS.MFT+  ( mftRecordCount+  , readAllMFTRecords+  ) where++import qualified Data.ByteString     as BS++import           NTFS.Attribute.Data (FileData (..), parseDataAttribute)+import           NTFS.BootSector+import           NTFS.MFT.Attribute+import           NTFS.MFT.Record+import           NTFS.Types+import           NTFS.Volume++-- | Number of records in the MFT, from the size of record 0's @$DATA@.+mftRecordCount :: Volume -> IO (Either ParseError Int)+mftRecordCount volume = do+  bytes <- readMFTRecordBytes volume (MFTRef 0)+  pure $ do+    raw <- bytes+    record <- parseMFTRecord sectorBytes raw+    dataAttributes <- mapM parseAttribute (filter isData (recordAttributes record))+    let unnamed = filter (maybe True BS.null . attributeName) dataAttributes+    case unnamed of+      [] -> Left (InvalidValue "$MFT has no unnamed $DATA attribute")+      attribute:_ -> do+        value <- parseDataAttribute attribute+        ClusterSize recordSize <- mftRecordSize (volumeBootSector volume)+        let total =+              case value of+                ResidentData valueBytes -> toInteger (BS.length valueBytes)+                NonResidentData _ _ realSize _ -> toInteger realSize+        Right (fromIntegral (total `div` toInteger recordSize))+  where+    sectorBytes = bsBytesPerSector (volumeBootSector volume)+    isData raw = rawAttributeType raw == attributeTypeData++-- | Read and parse every MFT record in order.+-- A malformed record stops the enumeration with an error.+readAllMFTRecords :: Volume -> IO (Either ParseError [MFTRecord])+readAllMFTRecords volume = do+  count <- mftRecordCount volume+  case count of+    Left err    -> pure (Left err)+    Right limit -> go 0 limit []+  where+    sectorBytes = bsBytesPerSector (volumeBootSector volume)+    go index limit acc+      | index >= limit = pure (Right (reverse acc))+      | otherwise = do+          bytes <- readMFTRecordBytes volume (MFTRef (fromIntegral index))+          case bytes >>= parseMFTRecord sectorBytes of+            Left err     -> pure (Left err)+            Right record -> go (index + 1) limit (record : acc)
src/NTFS/Volume.hs view
@@ -5,12 +5,15 @@   , clusterOffset   , mftOffset   , readMFTRecordBytes+  , readData   ) where -import qualified Data.ByteString as BS-import           System.IO       (Handle, SeekMode (AbsoluteSeek), hSeek)+import qualified Data.ByteString     as BS+import           System.IO           (Handle, SeekMode (AbsoluteSeek), hSeek) +import           NTFS.Attribute.Data (FileData (..)) import           NTFS.BootSector+import           NTFS.Runlist        (DataRun (..)) import           NTFS.Types  -- | An open NTFS volume backed by a seekable handle.@@ -49,3 +52,31 @@       if fromIntegral (BS.length bytes) == size         then pure (Right bytes)         else pure (Left (UnexpectedEndOfData "MFT record is truncated"))++-- | Read the bytes described by a @$DATA@ attribute.+-- Sparse runs are returned as zero bytes; the result is trimmed to the real size.+readData :: Volume -> FileData -> IO (Either ParseError BS.ByteString)+readData _ (ResidentData bytes) = pure (Right bytes)+readData volume (NonResidentData runs realSize _ _) = do+  results <- sequence (map (readRun volume) runs)+  pure $ do+    chunks <- sequence results+    let bytes = BS.concat chunks+    let total = fromIntegral (BS.length bytes) :: Integer+    if fromIntegral realSize > total+      then Left (UnexpectedEndOfData "$DATA is shorter than its real size")+      else Right (BS.take (fromIntegral realSize) bytes)++readRun :: Volume -> DataRun -> IO (Either ParseError BS.ByteString)+readRun volume run =+  case runLCN run of+    Nothing -> pure (Right (BS.replicate (fromIntegral size) 0))+    Just lcn -> do+      hSeek (volumeHandle volume) AbsoluteSeek (clusterOffset volume lcn)+      bytes <- BS.hGet (volumeHandle volume) (fromIntegral size)+      if fromIntegral (BS.length bytes) == size+        then pure (Right bytes)+        else pure (Left (UnexpectedEndOfData "data run is truncated"))+  where+    ClusterSize clusterBytes = bytesPerCluster (volumeBootSector volume)+    size = toInteger (runLength run) * toInteger clusterBytes
test/Spec.hs view
@@ -17,6 +17,8 @@ import           NTFS.Attribute.FileName import           NTFS.Attribute.StandardInformation import           NTFS.BootSector+import           NTFS.File+import           NTFS.MFT import           NTFS.MFT.Attribute import           NTFS.MFT.Record import           NTFS.Runlist@@ -47,8 +49,12 @@       , ("resident data attribute", pure testResidentData)       , ("non-resident data attribute", pure testNonResidentData)       , ("standard information attribute", pure testStandardInformation)+      , ("short standard information attribute", pure testShortStandardInformation)       , ("file name attribute", pure testFileName)       , ("short file name attribute", pure testShortFileName)+      , ("file entry from MFT record", pure testFileEntry)+      , ("read resident and non-resident data", testReadData)+      , ("enumerate MFT records", testReadAllMFTRecords)       ]   unless (and results) exitFailure @@ -234,6 +240,23 @@         && standardUpdateSequence info == 0x1234     Left _ -> False +testShortStandardInformation :: Bool+testShortStandardInformation =+  case parseAttribute+    ( residentAttributeOf+        attributeTypeStandardInformation+        (BS.take 0x30 standardInformationFixture)+    )+    >>= parseStandardInformation of+    Right info ->+      standardCreationTime info == 0x11+        && standardFileAttributes info == 0x20+        && standardClassId info == 0x10+        && standardOwnerId info == 0+        && standardQuotaCharged info == 0+        && standardUpdateSequence info == 0+    Left _ -> False+ testFileName :: Bool testFileName =   case parseAttribute (residentAttributeOf attributeTypeFileName fileNameFixture) >>= parseFileName of@@ -257,6 +280,88 @@     Left _  -> True     Right _ -> False +testFileEntry :: Bool+testFileEntry =+  case parseFileEntry record of+    Right entry ->+      entryRecordNumber entry == 9+        && isEntryInUse entry+        && isEntryDirectory entry+        && map fileNameName (entryFileNames entry) == ["AB"]+        && maybe False ((== 0x11) . standardCreationTime) (entryStandardInformation entry)+        && map fst (entryData entry) == [Nothing]+        && map snd (entryData entry) == [ResidentData (BS.replicate 0x30 0xab)]+    Left _ -> False+  where+    record =+      ( case parseMFTRecord 512 mftRecordFixture of+          Right value -> value+          Left _      -> error "invalid MFT fixture"+      )+        { recordAttributes =+            [ residentAttributeOf attributeTypeStandardInformation standardInformationFixture+            , residentAttributeOf attributeTypeFileName fileNameFixture+            , residentDataAttribute+            , RawAttribute 0x90 (BS.replicate 8 0)+            ]+        }++testReadData :: IO Bool+testReadData = do+  tmpDir <- getTemporaryDirectory+  (path, handle) <- openBinaryTempFile tmpDir "ntfs-read-data-test.img"+  let runs =+        [ DataRun (VCN 0) (Just (LCN 4)) 1+        , DataRun (VCN 1) Nothing 1+        , DataRun (VCN 2) (Just (LCN 6)) 1+        ]+      expected =+        BS.concat+          [ BS.replicate 4096 0x11+          , BS.replicate 4096 0+          , BS.replicate 4096 0x22+          ]+      check = do+        BS.hPut handle bootSector+        opened <- openVolume handle+        case opened of+          Left _ -> pure False+          Right volume -> do+            hSeek handle AbsoluteSeek (clusterOffset volume (LCN 4))+            BS.hPut handle (BS.replicate 4096 0x11)+            hSeek handle AbsoluteSeek (clusterOffset volume (LCN 6))+            BS.hPut handle (BS.replicate 4096 0x22)+            hFlush handle+            resident <- readData volume (ResidentData (BS.pack [1, 2, 3]))+            nonResident <- readData volume (NonResidentData runs 0x3000 0x3000 0x3000)+            pure+              ( resident == Right (BS.pack [1, 2, 3])+                  && nonResident == Right expected+              )+  check `finally` (hClose handle >> removeFile path)++testReadAllMFTRecords :: IO Bool+testReadAllMFTRecords = do+  tmpDir <- getTemporaryDirectory+  (path, handle) <- openBinaryTempFile tmpDir "ntfs-mft-enum-test.img"+  let check = do+        BS.hPut handle bootSector+        hSeek handle AbsoluteSeek 16384+        BS.hPut handle mftDataRecordFixture+        BS.hPut handle mftRecordFixture+        hFlush handle+        opened <- openVolume handle+        case opened of+          Left _ -> pure False+          Right volume -> do+            count <- mftRecordCount volume+            records <- readAllMFTRecords volume+            pure+              ( count == Right 2+                  && fmap (map recordNumber) records == Right [0, 9]+              )+  check `finally` (hClose handle >> removeFile path)+ bootSector :: BS.ByteString bootSector =   build@@ -270,6 +375,42 @@     , (0x44, [0xf7])     , (0x48, word64Bytes 0x1234)     , (0x1fe, [0x55, 0xaa])+    ]++mftDataRecordFixture :: BS.ByteString+mftDataRecordFixture =+  build+    (BS.replicate 1024 0)+    [ (0x00, [0x46, 0x49, 0x4c, 0x45])+    , (0x04, word16Bytes 0x30)+    , (0x06, word16Bytes 3)+    , (0x10, word16Bytes 1)+    , (0x12, word16Bytes 1)+    , (0x14, word16Bytes 0x38)+    , (0x16, word16Bytes 1)+    , (0x18, word32Bytes 0x7c)+    , (0x1c, word32Bytes 0x400)+    , (0x20, word64Bytes 0)+    , (0x28, word16Bytes 1)+    , (0x2c, word32Bytes 0)+    , (0x30, word16Bytes 0xaa55)+    , (0x32, word16Bytes 0x1111)+    , (0x34, word16Bytes 0x2222)+    , (0x38, word32Bytes 0x80 ++ word32Bytes 0x44)+    , (0x40, [0x01])+    , (0x41, [0x00])+    , (0x42, word16Bytes 0)+    , (0x44, word16Bytes 0)+    , (0x46, word16Bytes 0)+    , (0x48, word64Bytes 0)+    , (0x50, word64Bytes 1)+    , (0x58, word16Bytes 0x40)+    , (0x60, word64Bytes 0x800)+    , (0x68, word64Bytes 0x800)+    , (0x70, word64Bytes 0x800)+    , (0x78, [0x11, 0x02, 0x04, 0x00])+    , (0x1fe, word16Bytes 0xaa55)+    , (0x3fe, word16Bytes 0xaa55)     ]  mftRecordFixture :: BS.ByteString