dissect.fat 3.14.dev2__py3-none-any.whl → 3.14.dev4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dissect/fat/__init__.py CHANGED
@@ -1,31 +1,40 @@
1
1
  from __future__ import annotations
2
2
 
3
- from dissect.fat.exceptions import (
3
+ from dissect.fat.base import FatType
4
+ from dissect.fat.c_exfat import c_exfat
5
+ from dissect.fat.c_fat import c_fat
6
+ from dissect.fat.exception import (
4
7
  BadClusterError,
5
- EmptyDirectoryError,
8
+ DeletedDirectoryError,
6
9
  Error,
7
10
  FileNotFoundError,
8
11
  FreeClusterError,
9
- InvalidBPB,
12
+ InvalidBootSector,
10
13
  InvalidDirectoryError,
11
14
  InvalidHeaderMagic,
12
15
  LastEmptyDirectoryError,
13
16
  NotADirectoryError,
14
17
  )
15
18
  from dissect.fat.exfat import ExFAT
16
- from dissect.fat.fat import FATFS
19
+ from dissect.fat.fat import FAT12, FAT16, FAT32, FATFS
17
20
 
18
21
  __all__ = [
22
+ "FAT12",
23
+ "FAT16",
24
+ "FAT32",
19
25
  "FATFS",
20
26
  "BadClusterError",
21
- "EmptyDirectoryError",
27
+ "DeletedDirectoryError",
22
28
  "Error",
23
29
  "ExFAT",
30
+ "FatType",
24
31
  "FileNotFoundError",
25
32
  "FreeClusterError",
26
- "InvalidBPB",
33
+ "InvalidBootSector",
27
34
  "InvalidDirectoryError",
28
35
  "InvalidHeaderMagic",
29
36
  "LastEmptyDirectoryError",
30
37
  "NotADirectoryError",
38
+ "c_exfat",
39
+ "c_fat",
31
40
  ]
dissect/fat/base.py ADDED
@@ -0,0 +1,333 @@
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import math
5
+ import struct
6
+ from enum import Enum, auto
7
+ from functools import cache, cached_property, lru_cache
8
+ from operator import itemgetter
9
+ from typing import TYPE_CHECKING, Any, BinaryIO, TypeVar
10
+
11
+ from dissect.util.stream import RunlistStream
12
+
13
+ from dissect.fat.c_fat import c_fat
14
+ from dissect.fat.exception import (
15
+ BadClusterError,
16
+ DeletedDirectoryError,
17
+ FileNotFoundError,
18
+ FreeClusterError,
19
+ LastEmptyDirectoryError,
20
+ NotADirectoryError,
21
+ )
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Iterator
25
+
26
+
27
+ class FatType(Enum):
28
+ FAT12 = auto()
29
+ FAT16 = auto()
30
+ FAT32 = auto()
31
+ EXFAT = auto()
32
+
33
+
34
+ class FS:
35
+ type: FatType
36
+
37
+ sector_size: int
38
+ cluster_size: int
39
+
40
+ fat: FAT
41
+ data: BinaryIO
42
+
43
+ volume_label: str
44
+ volume_id: str
45
+
46
+ root: BaseDirectoryEntry
47
+
48
+ def get(self, path: str, dirent: BaseDirectoryEntry | None = None) -> BaseDirectoryEntry:
49
+ """Get a directory entry by path.
50
+
51
+ Args:
52
+ path: The path to the directory entry.
53
+ dirent: The directory entry to start the search from. Defaults to the root directory.
54
+ """
55
+ dirent = dirent or self.root
56
+
57
+ # Programmatically we will often use the `/` separator, so replace it with the native path separator of FAT
58
+ # `/` is an illegal character in FAT filenames, so it's safe to replace
59
+ parts = path.replace("/", "\\").split("\\")
60
+ for part in parts:
61
+ if not part:
62
+ continue
63
+
64
+ if dirent is self.root and part in (".", ".."):
65
+ continue
66
+
67
+ part_upper = part.upper()
68
+ for child in dirent.iterdir():
69
+ if self._match(part_upper, child):
70
+ dirent = child
71
+ break
72
+ else:
73
+ raise FileNotFoundError(f"File not found: {path}")
74
+
75
+ return dirent
76
+
77
+ def _match(self, name: str, dirent: BaseDirectoryEntry) -> bool:
78
+ """Return whether the given name matches the directory entry's name."""
79
+ return name == dirent.name.upper()
80
+
81
+
82
+ class BaseDirectoryEntry:
83
+ """Base class for FAT directory entries.
84
+
85
+ Args:
86
+ fs: The filesystem this directory entry belongs to.
87
+ fh: File-like object positioned at the start of the directory entry to read.
88
+ """
89
+
90
+ def __init__(self, fs: FS, fh: BinaryIO | None):
91
+ self.fs = fs
92
+
93
+ if fh is not None:
94
+ self.dirent, self.secondary_dirents = self._read_dirent(fh)
95
+ else:
96
+ self.dirent, self.secondary_dirents = None, []
97
+
98
+ self.dataruns = cache(self.dataruns)
99
+
100
+ def __repr__(self) -> str:
101
+ return f"<{self.__class__.__name__} name={self.name!r}>"
102
+
103
+ def _read_dirent(self, fh: BinaryIO | None) -> tuple[Any | None, list[Any]]:
104
+ """Read a directory entry from the given file handle, handling secondary entries if present.
105
+
106
+ Args:
107
+ fh: File-like object positioned at the start of the directory entry to read.
108
+
109
+ Returns:
110
+ A tuple containing the directory entry and a list of secondary directory entries.
111
+ """
112
+ raise NotImplementedError
113
+
114
+ @cached_property
115
+ def name(self) -> str:
116
+ """Return the canonical name of the directory entry."""
117
+ raise NotImplementedError
118
+
119
+ @cached_property
120
+ def attr(self) -> int:
121
+ """Return the attribute value of the directory entry."""
122
+ raise NotImplementedError
123
+
124
+ @cached_property
125
+ def size(self) -> int:
126
+ """Return the size of the directory entry in bytes."""
127
+ return sum(map(itemgetter(1), self.dataruns())) * self.fs.cluster_size
128
+
129
+ @cached_property
130
+ def cluster(self) -> int:
131
+ """Return the starting cluster number of the directory entry."""
132
+ raise NotImplementedError
133
+
134
+ @cached_property
135
+ def ctime(self) -> datetime.datetime:
136
+ """Return the creation time of the directory entry."""
137
+ return datetime.datetime(1980, 1, 1) # noqa: DTZ001
138
+
139
+ @cached_property
140
+ def atime(self) -> datetime.datetime:
141
+ """Return the last access time of the directory entry."""
142
+ return datetime.datetime(1980, 1, 1) # noqa: DTZ001
143
+
144
+ @cached_property
145
+ def mtime(self) -> datetime.datetime:
146
+ """Return the last modification time of the directory entry."""
147
+ return datetime.datetime(1980, 1, 1) # noqa: DTZ001
148
+
149
+ def is_readonly(self) -> bool:
150
+ """Return whether the directory entry is read-only."""
151
+ return bool(self.attr & c_fat.FAT_DIRENT_ATTR_READ_ONLY)
152
+
153
+ def is_hidden(self) -> bool:
154
+ """Return whether the directory entry is hidden."""
155
+ return bool(self.attr & c_fat.FAT_DIRENT_ATTR_HIDDEN)
156
+
157
+ def is_system(self) -> bool:
158
+ """Return whether the directory entry is a system file."""
159
+ return bool(self.attr & c_fat.FAT_DIRENT_ATTR_SYSTEM)
160
+
161
+ def is_volume_id(self) -> bool:
162
+ """Return whether the directory entry is a volume ID."""
163
+ return bool(self.attr & c_fat.FAT_DIRENT_ATTR_VOLUME_ID)
164
+
165
+ def is_directory(self) -> bool:
166
+ """Return whether the directory entry is a directory."""
167
+ return bool(self.attr & c_fat.FAT_DIRENT_ATTR_DIRECTORY)
168
+
169
+ def is_archive(self) -> bool:
170
+ """Return whether the directory entry has the archive attribute set."""
171
+ return bool(self.attr & c_fat.FAT_DIRENT_ATTR_ARCHIVE)
172
+
173
+ def listdir(self) -> list[str]:
174
+ """Return a list of names of the entries in the directory."""
175
+ return [entry.name for entry in self.iterdir()]
176
+
177
+ def iterdir(self) -> Iterator[BaseDirectoryEntry]:
178
+ """Yield the directory entries in the directory."""
179
+ if not self.is_directory():
180
+ raise NotADirectoryError(self.name)
181
+
182
+ with self.open() as fh:
183
+ yield from self._iterdir(fh)
184
+
185
+ def _iterdir(self, fh: BinaryIO) -> Iterator[BaseDirectoryEntry]:
186
+ """Yield the directory entries in the directory from the given file handle.
187
+
188
+ Args:
189
+ fh: File-like object positioned at the start of the directory data to read.
190
+ """
191
+ raise NotImplementedError
192
+
193
+ def dataruns(self) -> list[tuple[int, int]]:
194
+ """Return the runlist of the directory entry."""
195
+ return [] if self.cluster == FAT.FREE_CLUSTER else list(self.fs.fat.runlist(self.cluster))
196
+
197
+ def open(self) -> RunlistStream:
198
+ """Open the directory entry for reading."""
199
+ return RunlistStream(self.fs.data, self.dataruns(), self.size, self.fs.cluster_size)
200
+
201
+
202
+ T = TypeVar("T", bound=BaseDirectoryEntry)
203
+
204
+
205
+ def iter_dirent(cls: type[T], fs: FS, fh: BinaryIO) -> Iterator[T]:
206
+ while True:
207
+ try:
208
+ yield cls(fs, fh)
209
+ except DeletedDirectoryError: # noqa: PERF203
210
+ continue
211
+ except (LastEmptyDirectoryError, EOFError):
212
+ break
213
+
214
+
215
+ _H = struct.Struct("<H")
216
+ _I = struct.Struct("<I")
217
+
218
+
219
+ class FAT:
220
+ """File Allocation Table (FAT) implementation.
221
+
222
+ Args:
223
+ fh: File-like object containing the FAT.
224
+ size: Size of the FAT in bytes.
225
+ bits_per_entry: Number of bits per FAT entry.
226
+ """
227
+
228
+ DATA_CLUSTER_MIN = 0x00000002
229
+ DATA_CLUSTER_MAX = 0xFFFFFFEF
230
+ END_OF_CLUSTER_MIN = 0xFFFFFFF8
231
+ END_OF_CLUSTER_MAX = 0xFFFFFFFF
232
+ BAD_CLUSTER = 0xFFFFFFF7
233
+ FREE_CLUSTER = 0x00000000
234
+
235
+ FAT12_EOC = 0x000000FF0
236
+
237
+ def __init__(self, fh: BinaryIO, size: int, bits_per_entry: int):
238
+ self.fh = fh
239
+ self.bits_per_entry = bits_per_entry
240
+ self.entry_count = int(size // math.ceil(self.bits_per_entry / 8))
241
+
242
+ self.get = lru_cache(4096)(self.get)
243
+
244
+ def get(self, cluster: int) -> int | None:
245
+ """Get the FAT entry for a given cluster.
246
+
247
+ Args:
248
+ cluster: The cluster number to get the FAT entry for.
249
+ """
250
+ if cluster >= self.entry_count:
251
+ raise ValueError(f"Cluster exceeds FAT entry count: {cluster} >= {self.entry_count}")
252
+
253
+ if self.bits_per_entry == 12:
254
+ offset_in_fat = cluster + (cluster // 2)
255
+ self.fh.seek(offset_in_fat)
256
+ value = _H.unpack(self.fh.read(2))[0]
257
+ return value >> 4 if cluster & 1 else value & 0x0FFF
258
+
259
+ if self.bits_per_entry == 16:
260
+ offset_in_fat = cluster * 2
261
+ self.fh.seek(offset_in_fat)
262
+ return _H.unpack(self.fh.read(2))[0]
263
+
264
+ if self.bits_per_entry == 28:
265
+ offset_in_fat = cluster * 4
266
+ self.fh.seek(offset_in_fat)
267
+ return _I.unpack(self.fh.read(4))[0] & 0x0FFFFFFF
268
+
269
+ if self.bits_per_entry == 32:
270
+ offset_in_fat = cluster * 4
271
+ self.fh.seek(offset_in_fat)
272
+ return _I.unpack(self.fh.read(4))[0]
273
+
274
+ raise ValueError("Unsupported FAT type")
275
+
276
+ def chain(self, cluster: int) -> Iterator[int]:
277
+ """Yield the cluster chain starting from a given cluster.
278
+
279
+ Args:
280
+ cluster: The starting cluster number.
281
+ """
282
+ bits = self.bits_per_entry
283
+
284
+ while True:
285
+ value = self.get(cluster)
286
+ if self.DATA_CLUSTER_MIN <= value <= mask(self.DATA_CLUSTER_MAX, bits):
287
+ yield cluster
288
+
289
+ # FAT12 special EOC
290
+ if self.bits_per_entry == 12 and value == self.FAT12_EOC:
291
+ yield cluster
292
+ break
293
+
294
+ if mask(self.END_OF_CLUSTER_MIN, bits) <= value <= mask(self.END_OF_CLUSTER_MAX, bits):
295
+ yield cluster
296
+ break
297
+
298
+ if value == mask(self.BAD_CLUSTER, bits):
299
+ raise BadClusterError(cluster)
300
+
301
+ if value == self.FREE_CLUSTER:
302
+ raise FreeClusterError(cluster)
303
+
304
+ cluster = value
305
+
306
+ def runlist(self, cluster: int, *, reserved: int = 2) -> Iterator[tuple[int, int]]:
307
+ """Create a runlist from a cluster chain.
308
+
309
+ On normal FAT filesystems, the first two clusters are reserved, so substract those.
310
+ Also combine consecutive clusters for a more efficient runlist.
311
+
312
+ Args:
313
+ cluster: The starting cluster number.
314
+ """
315
+ chain = self.chain(cluster)
316
+
317
+ run_start = next(chain) - reserved
318
+ run_size = 1
319
+
320
+ for cl in chain:
321
+ if cl == run_start + run_size:
322
+ run_size += 1
323
+ else:
324
+ yield (run_start, run_size)
325
+ run_start = cl - reserved
326
+ run_size = 1
327
+ else:
328
+ yield (run_start, run_size)
329
+
330
+
331
+ @lru_cache(128)
332
+ def mask(v: int, bits: int) -> int:
333
+ return v & ((1 << bits) - 1)