nathanhi / pyfatfs

Python based FAT12/FAT16/FAT32 implementation with VFAT support
https://pypi.org/project/pyfatfs/
MIT License
29 stars 14 forks source link

Open in-memory FS as RO? #21

Closed gavanderhoorn closed 2 years ago

gavanderhoorn commented 2 years ago

4bbf04e02c05b7a060cf0616ff4f76348c1c3f4a adds support for in-memory, io.BytesIO-backed FS to be opened via the new PyFatBytesIOFS(..) constructor.

Would it be possible to allow opening such FS in read-only mode as well, similar to how the regular, file-backed PyFatFS allows that?

I'm using pyfatfs for forensic-like work, and being able to prevent any-and-all writes to images would be very handy to have.

gavanderhoorn commented 2 years ago

Ah, I believe I may not have checked carefully enough. It appears it's already read-only, as this

https://github.com/nathanhi/pyfatfs/blob/a35586bfa2b1d3f8d4638142407db68f9318b86d/pyfatfs/PyFat.py#L124

isn't changed by PyFatBytesIOFS(..).


Edit: after opening a couple files from such an in-memory image, on closing pyfatfs throws:

Traceback (most recent call last):
  File "./test.py", line 68, in <module>
    print(f"Contents: {content}")
  File "/.../lib/python3.8/site-packages/pyfatfs/FatIO.py", line 115, in close
    self.fs.flush_fat()
  File "/.../lib/python3.8/site-packages/pyfatfs/__init__.py", line 31, in _wrapper
    return func(*args, **kwargs)
  File "/.../lib/python3.8/site-packages/pyfatfs/PyFat.py", line 37, in _wrapper
    raise PyFATException("Filesystem has been opened read-only, not "
pyfatfs._exceptions.PyFATException: Filesystem has been opened read-only, not able to perform a write operation!

would there be some way to avoid this, or should I just handle the exception?


Edit 2: am I correct if I say that PyFatBytesIOFS and PyFat don't implement context management? It appears PyFatFS does, but that's not what I'm using.

abrasive commented 2 years ago

@gavanderhoorn I ran into the same exception, it should be fixed using #23

gavanderhoorn commented 2 years ago

Thanks.

nathanhi commented 2 years ago

Edit 2: am I correct if I say that PyFatBytesIOFS and PyFat don't implement context management? It appears PyFatFS does, but that's not what I'm using.

PyFat implements a context manager, PyFatFS and PyFatBytesIOFS are both implementing the PyFilesystem2 FS class, which also provides a context manager:

>>> from pyfatfs.PyFatFS import PyFatFS
>>> with PyFatFS("/dev/sda1.img", read_only=True) as fs:
...     print(fs.listdir("/"))
... 
/home/nathanhi/src/github/pyfatfs/pyfatfs/PyFat.py:237: UserWarning: Filesystem was not cleanly unmounted on last access. Check for data corruption.
['grub', 'EFI']