Skip to content

Handler

Handler

Provides a file handler class that saves files directly to disk.

This module provides a file handler class that saves files directly to disk. It is used by the Volatility3 CLI to save files to disk.

Example

The file handler class can be used as follows:

$ python3
>>> from volatility3.cli import create_file_handler
>>> file_handler = create_file_handler("output")
>>> file = file_handler("test.txt")
>>> file.write(b"Hello, world!")
>>> file.close()
Todo
  • For now, this module only provides a file handler class that saves files directly to disk. In the future, it could be extended to provide other file handlers as well.

create_file_handler(output_dir)

Create a file handler class that saves files directly to disk.

Parameters:

Name Type Description Default
output_dir str

The directory where the files should be saved. If None, raises a TypeError.

required

Returns: type: A file handler class that saves files directly to disk.

Source code in pydfirram/core/handler.py
 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
def create_file_handler(output_dir: Optional[str]) -> type:
    """Create a file handler class that saves files directly to disk.

    Args:
        output_dir (str): The directory where the files should be saved.
                          If None, raises a TypeError.
    Returns:
        type: A file handler class that saves files directly to disk.
    """

    class CLIFileHandler(V3FileHandlerInterface): # type: ignore
        """The FileHandler from Volatility3 CLI.
        """
        def _get_final_filename(self) -> str:
            """Gets the final filename for the saved file."""
            if output_dir is None:
                raise TypeError("Output directory is not a string")

            os.makedirs(output_dir, exist_ok=True)
            if self.preferred_filename is None:
                raise TypeError("No preferred filename")

            pref_name_array = self.preferred_filename.split(".")

            filename, extension = (
                os.path.join(output_dir, ".".join(pref_name_array[:-1])),
                pref_name_array[-1],
            )
            output_filename = f"{filename}.{extension}"

            if os.path.exists(output_filename):
                os.remove(output_filename)

            return output_filename

        def close(self) -> None:
            """ V3FileHandlerInterface require to implement this method """

    class CLIDirectFileHandler(CLIFileHandler):
        """A file handler class that saves files directly to disk.
        """
        def __init__(self, filename: str) -> None:
            fd, temp_name = tempfile.mkstemp(
                suffix  = ".vol3",
                prefix  = "tmp_",
                dir     = output_dir,
            )

            # allow `io.open()` without using `with` context
            # pylint: disable=R1732
            self._file = io.open(fd, mode="w+b")
            CLIFileHandler.__init__(self, filename) # type: ignore

            for attr in dir(self._file):
                if not attr.startswith("_") and attr not in [
                    "closed",
                    "close",
                    "mode",
                    "name",
                ]:
                    setattr(self, attr, getattr(self._file, attr))

            self._name = temp_name

        def __getattr__(self, item: Any) -> Any:
            return getattr(self._file, item)

        ## properties

        @property
        def closed(self) -> bool:
            """Returns whether the file is closed."""
            return self._file.closed

        @property
        def mode(self) -> str:
            """Returns the mode of the file."""
            return self._file.mode

        @property
        def name(self) -> str:
            """Returns the name of the file."""
            return self._file.name

        ## methods

        def close(self) -> None:
            """Closes and commits the file
            by moving the temporary file to the correct name.
            """
            # Don't overcommit
            if self._file.closed:
                return
            self._file.close()
            output_filename = self._get_final_filename()
            os.rename(self._name, output_filename)

    return CLIDirectFileHandler