repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
log2timeline/dfvfs
dfvfs/resolver/cache.py
ObjectsCache.ReleaseObject
def ReleaseObject(self, identifier): """Releases a cached object based on the identifier. This method decrements the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. RuntimeError: if the cache value is missing. """ if identifier not in self._values: raise KeyError('Missing cached object for identifier: {0:s}'.format( identifier)) cache_value = self._values[identifier] if not cache_value: raise RuntimeError('Missing cache value for identifier: {0:s}'.format( identifier)) cache_value.DecrementReferenceCount()
python
def ReleaseObject(self, identifier): """Releases a cached object based on the identifier. This method decrements the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. RuntimeError: if the cache value is missing. """ if identifier not in self._values: raise KeyError('Missing cached object for identifier: {0:s}'.format( identifier)) cache_value = self._values[identifier] if not cache_value: raise RuntimeError('Missing cache value for identifier: {0:s}'.format( identifier)) cache_value.DecrementReferenceCount()
[ "def", "ReleaseObject", "(", "self", ",", "identifier", ")", ":", "if", "identifier", "not", "in", "self", ".", "_values", ":", "raise", "KeyError", "(", "'Missing cached object for identifier: {0:s}'", ".", "format", "(", "identifier", ")", ")", "cache_value", ...
Releases a cached object based on the identifier. This method decrements the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. RuntimeError: if the cache value is missing.
[ "Releases", "a", "cached", "object", "based", "on", "the", "identifier", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/cache.py#L172-L193
train
208,300
log2timeline/dfvfs
dfvfs/resolver/cache.py
ObjectsCache.RemoveObject
def RemoveObject(self, identifier): """Removes a cached object based on the identifier. This method ignores the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. """ if identifier not in self._values: raise KeyError('Missing cached object for identifier: {0:s}'.format( identifier)) del self._values[identifier]
python
def RemoveObject(self, identifier): """Removes a cached object based on the identifier. This method ignores the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache. """ if identifier not in self._values: raise KeyError('Missing cached object for identifier: {0:s}'.format( identifier)) del self._values[identifier]
[ "def", "RemoveObject", "(", "self", ",", "identifier", ")", ":", "if", "identifier", "not", "in", "self", ".", "_values", ":", "raise", "KeyError", "(", "'Missing cached object for identifier: {0:s}'", ".", "format", "(", "identifier", ")", ")", "del", "self", ...
Removes a cached object based on the identifier. This method ignores the cache value reference count. Args: identifier (str): VFS object identifier. Raises: KeyError: if the VFS object is not found in the cache.
[ "Removes", "a", "cached", "object", "based", "on", "the", "identifier", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/cache.py#L195-L210
train
208,301
log2timeline/dfvfs
dfvfs/vfs/ntfs_file_entry.py
NTFSFileEntry.GetSecurityDescriptor
def GetSecurityDescriptor(self): """Retrieves the security descriptor. Returns: pyfwnt.security_descriptor: security descriptor. """ fwnt_security_descriptor = pyfwnt.security_descriptor() fwnt_security_descriptor.copy_from_byte_stream( self._fsntfs_file_entry.security_descriptor_data) return fwnt_security_descriptor
python
def GetSecurityDescriptor(self): """Retrieves the security descriptor. Returns: pyfwnt.security_descriptor: security descriptor. """ fwnt_security_descriptor = pyfwnt.security_descriptor() fwnt_security_descriptor.copy_from_byte_stream( self._fsntfs_file_entry.security_descriptor_data) return fwnt_security_descriptor
[ "def", "GetSecurityDescriptor", "(", "self", ")", ":", "fwnt_security_descriptor", "=", "pyfwnt", ".", "security_descriptor", "(", ")", "fwnt_security_descriptor", ".", "copy_from_byte_stream", "(", "self", ".", "_fsntfs_file_entry", ".", "security_descriptor_data", ")", ...
Retrieves the security descriptor. Returns: pyfwnt.security_descriptor: security descriptor.
[ "Retrieves", "the", "security", "descriptor", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/ntfs_file_entry.py#L541-L551
train
208,302
log2timeline/dfvfs
dfvfs/lib/cpio.py
CPIOArchiveFile._ReadFileEntries
def _ReadFileEntries(self, file_object): """Reads the file entries from the cpio archive. Args: file_object (FileIO): file-like object. """ self._file_entries = {} file_offset = 0 while file_offset < self._file_size or self._file_size == 0: file_entry = self._ReadFileEntry(file_object, file_offset) file_offset += file_entry.size if file_entry.path == 'TRAILER!!!': break if file_entry.path in self._file_entries: # TODO: alert on file entries with duplicate paths? continue self._file_entries[file_entry.path] = file_entry
python
def _ReadFileEntries(self, file_object): """Reads the file entries from the cpio archive. Args: file_object (FileIO): file-like object. """ self._file_entries = {} file_offset = 0 while file_offset < self._file_size or self._file_size == 0: file_entry = self._ReadFileEntry(file_object, file_offset) file_offset += file_entry.size if file_entry.path == 'TRAILER!!!': break if file_entry.path in self._file_entries: # TODO: alert on file entries with duplicate paths? continue self._file_entries[file_entry.path] = file_entry
[ "def", "_ReadFileEntries", "(", "self", ",", "file_object", ")", ":", "self", ".", "_file_entries", "=", "{", "}", "file_offset", "=", "0", "while", "file_offset", "<", "self", ".", "_file_size", "or", "self", ".", "_file_size", "==", "0", ":", "file_entry...
Reads the file entries from the cpio archive. Args: file_object (FileIO): file-like object.
[ "Reads", "the", "file", "entries", "from", "the", "cpio", "archive", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/cpio.py#L231-L250
train
208,303
log2timeline/dfvfs
dfvfs/lib/cpio.py
CPIOArchiveFile.GetFileEntries
def GetFileEntries(self, path_prefix=''): """Retrieves the file entries. Args: path_prefix (str): path prefix. Yields: CPIOArchiveFileEntry: a CPIO archive file entry. """ if self._file_entries: for path, file_entry in iter(self._file_entries.items()): if path.startswith(path_prefix): yield file_entry
python
def GetFileEntries(self, path_prefix=''): """Retrieves the file entries. Args: path_prefix (str): path prefix. Yields: CPIOArchiveFileEntry: a CPIO archive file entry. """ if self._file_entries: for path, file_entry in iter(self._file_entries.items()): if path.startswith(path_prefix): yield file_entry
[ "def", "GetFileEntries", "(", "self", ",", "path_prefix", "=", "''", ")", ":", "if", "self", ".", "_file_entries", ":", "for", "path", ",", "file_entry", "in", "iter", "(", "self", ".", "_file_entries", ".", "items", "(", ")", ")", ":", "if", "path", ...
Retrieves the file entries. Args: path_prefix (str): path prefix. Yields: CPIOArchiveFileEntry: a CPIO archive file entry.
[ "Retrieves", "the", "file", "entries", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/cpio.py#L269-L281
train
208,304
log2timeline/dfvfs
dfvfs/lib/cpio.py
CPIOArchiveFile.Open
def Open(self, file_object): """Opens the CPIO archive file. Args: file_object (FileIO): a file-like object. Raises: IOError: if the file format signature is not supported. OSError: if the file format signature is not supported. """ file_object.seek(0, os.SEEK_SET) signature_data = file_object.read(6) self.file_format = None if len(signature_data) > 2: if signature_data[:2] == self._CPIO_SIGNATURE_BINARY_BIG_ENDIAN: self.file_format = 'bin-big-endian' elif signature_data[:2] == self._CPIO_SIGNATURE_BINARY_LITTLE_ENDIAN: self.file_format = 'bin-little-endian' elif signature_data == self._CPIO_SIGNATURE_PORTABLE_ASCII: self.file_format = 'odc' elif signature_data == self._CPIO_SIGNATURE_NEW_ASCII: self.file_format = 'newc' elif signature_data == self._CPIO_SIGNATURE_NEW_ASCII_WITH_CHECKSUM: self.file_format = 'crc' if self.file_format is None: raise IOError('Unsupported CPIO format.') self._file_object = file_object self._file_size = file_object.get_size() self._ReadFileEntries(self._file_object)
python
def Open(self, file_object): """Opens the CPIO archive file. Args: file_object (FileIO): a file-like object. Raises: IOError: if the file format signature is not supported. OSError: if the file format signature is not supported. """ file_object.seek(0, os.SEEK_SET) signature_data = file_object.read(6) self.file_format = None if len(signature_data) > 2: if signature_data[:2] == self._CPIO_SIGNATURE_BINARY_BIG_ENDIAN: self.file_format = 'bin-big-endian' elif signature_data[:2] == self._CPIO_SIGNATURE_BINARY_LITTLE_ENDIAN: self.file_format = 'bin-little-endian' elif signature_data == self._CPIO_SIGNATURE_PORTABLE_ASCII: self.file_format = 'odc' elif signature_data == self._CPIO_SIGNATURE_NEW_ASCII: self.file_format = 'newc' elif signature_data == self._CPIO_SIGNATURE_NEW_ASCII_WITH_CHECKSUM: self.file_format = 'crc' if self.file_format is None: raise IOError('Unsupported CPIO format.') self._file_object = file_object self._file_size = file_object.get_size() self._ReadFileEntries(self._file_object)
[ "def", "Open", "(", "self", ",", "file_object", ")", ":", "file_object", ".", "seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "signature_data", "=", "file_object", ".", "read", "(", "6", ")", "self", ".", "file_format", "=", "None", "if", "len", "...
Opens the CPIO archive file. Args: file_object (FileIO): a file-like object. Raises: IOError: if the file format signature is not supported. OSError: if the file format signature is not supported.
[ "Opens", "the", "CPIO", "archive", "file", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/cpio.py#L293-L325
train
208,305
log2timeline/dfvfs
dfvfs/lib/cpio.py
CPIOArchiveFile.ReadDataAtOffset
def ReadDataAtOffset(self, file_offset, size): """Reads a byte string from the file-like object at a specific offset. Args: file_offset (int): file offset. size (int): number of bytes to read. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed. """ self._file_object.seek(file_offset, os.SEEK_SET) return self._file_object.read(size)
python
def ReadDataAtOffset(self, file_offset, size): """Reads a byte string from the file-like object at a specific offset. Args: file_offset (int): file offset. size (int): number of bytes to read. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed. """ self._file_object.seek(file_offset, os.SEEK_SET) return self._file_object.read(size)
[ "def", "ReadDataAtOffset", "(", "self", ",", "file_offset", ",", "size", ")", ":", "self", ".", "_file_object", ".", "seek", "(", "file_offset", ",", "os", ".", "SEEK_SET", ")", "return", "self", ".", "_file_object", ".", "read", "(", "size", ")" ]
Reads a byte string from the file-like object at a specific offset. Args: file_offset (int): file offset. size (int): number of bytes to read. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed.
[ "Reads", "a", "byte", "string", "from", "the", "file", "-", "like", "object", "at", "a", "specific", "offset", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/cpio.py#L327-L342
train
208,306
log2timeline/dfvfs
dfvfs/vfs/ntfs_file_system.py
NTFSFileSystem.GetNTFSFileEntryByPathSpec
def GetNTFSFileEntryByPathSpec(self, path_spec): """Retrieves the NTFS file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: pyfsntfs.file_entry: NTFS file entry. Raises: PathSpecError: if the path specification is missing location and MFT entry. """ # Opening a file by MFT entry is faster than opening a file by location. # However we need the index of the corresponding $FILE_NAME MFT attribute. location = getattr(path_spec, 'location', None) mft_attribute = getattr(path_spec, 'mft_attribute', None) mft_entry = getattr(path_spec, 'mft_entry', None) if mft_attribute is not None and mft_entry is not None: fsntfs_file_entry = self._fsntfs_volume.get_file_entry(mft_entry) elif location is not None: fsntfs_file_entry = self._fsntfs_volume.get_file_entry_by_path(location) else: raise errors.PathSpecError( 'Path specification missing location and MFT entry.') return fsntfs_file_entry
python
def GetNTFSFileEntryByPathSpec(self, path_spec): """Retrieves the NTFS file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: pyfsntfs.file_entry: NTFS file entry. Raises: PathSpecError: if the path specification is missing location and MFT entry. """ # Opening a file by MFT entry is faster than opening a file by location. # However we need the index of the corresponding $FILE_NAME MFT attribute. location = getattr(path_spec, 'location', None) mft_attribute = getattr(path_spec, 'mft_attribute', None) mft_entry = getattr(path_spec, 'mft_entry', None) if mft_attribute is not None and mft_entry is not None: fsntfs_file_entry = self._fsntfs_volume.get_file_entry(mft_entry) elif location is not None: fsntfs_file_entry = self._fsntfs_volume.get_file_entry_by_path(location) else: raise errors.PathSpecError( 'Path specification missing location and MFT entry.') return fsntfs_file_entry
[ "def", "GetNTFSFileEntryByPathSpec", "(", "self", ",", "path_spec", ")", ":", "# Opening a file by MFT entry is faster than opening a file by location.", "# However we need the index of the corresponding $FILE_NAME MFT attribute.", "location", "=", "getattr", "(", "path_spec", ",", "...
Retrieves the NTFS file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: pyfsntfs.file_entry: NTFS file entry. Raises: PathSpecError: if the path specification is missing location and MFT entry.
[ "Retrieves", "the", "NTFS", "file", "entry", "for", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/ntfs_file_system.py#L150-L177
train
208,307
log2timeline/dfvfs
dfvfs/lib/raw.py
_RawGlobPathSpecWithAlphabeticalSchema
def _RawGlobPathSpecWithAlphabeticalSchema( file_system, parent_path_spec, segment_format, location, segment_length, upper_case=False): """Globs for path specifications according to an alphabetical naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format (str): naming schema of the segment file location. location (str): the base segment file location string. segment_length (int): length (number of characters) of the segment indicator. upper_case (Optional[bool]): True if the segment name is in upper case. Returns: list[PathSpec]: path specifications that match the glob. """ segment_number = 0 segment_files = [] while True: segment_index = segment_number segment_letters = [] while len(segment_letters) < segment_length: segment_index, remainder = divmod(segment_index, 26) if upper_case: segment_letters.append(chr(ord('A') + remainder)) else: segment_letters.append(chr(ord('a') + remainder)) # Reverse the segment letters list to form the extension. segment_letters = ''.join(segment_letters[::-1]) segment_location = segment_format.format(location, segment_letters) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec) kwargs['location'] = segment_location if parent_path_spec.parent is not None: kwargs['parent'] = parent_path_spec.parent segment_path_spec = path_spec_factory.Factory.NewPathSpec( parent_path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(segment_path_spec): break segment_files.append(segment_path_spec) segment_number += 1 return segment_files
python
def _RawGlobPathSpecWithAlphabeticalSchema( file_system, parent_path_spec, segment_format, location, segment_length, upper_case=False): """Globs for path specifications according to an alphabetical naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format (str): naming schema of the segment file location. location (str): the base segment file location string. segment_length (int): length (number of characters) of the segment indicator. upper_case (Optional[bool]): True if the segment name is in upper case. Returns: list[PathSpec]: path specifications that match the glob. """ segment_number = 0 segment_files = [] while True: segment_index = segment_number segment_letters = [] while len(segment_letters) < segment_length: segment_index, remainder = divmod(segment_index, 26) if upper_case: segment_letters.append(chr(ord('A') + remainder)) else: segment_letters.append(chr(ord('a') + remainder)) # Reverse the segment letters list to form the extension. segment_letters = ''.join(segment_letters[::-1]) segment_location = segment_format.format(location, segment_letters) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec) kwargs['location'] = segment_location if parent_path_spec.parent is not None: kwargs['parent'] = parent_path_spec.parent segment_path_spec = path_spec_factory.Factory.NewPathSpec( parent_path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(segment_path_spec): break segment_files.append(segment_path_spec) segment_number += 1 return segment_files
[ "def", "_RawGlobPathSpecWithAlphabeticalSchema", "(", "file_system", ",", "parent_path_spec", ",", "segment_format", ",", "location", ",", "segment_length", ",", "upper_case", "=", "False", ")", ":", "segment_number", "=", "0", "segment_files", "=", "[", "]", "while...
Globs for path specifications according to an alphabetical naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format (str): naming schema of the segment file location. location (str): the base segment file location string. segment_length (int): length (number of characters) of the segment indicator. upper_case (Optional[bool]): True if the segment name is in upper case. Returns: list[PathSpec]: path specifications that match the glob.
[ "Globs", "for", "path", "specifications", "according", "to", "an", "alphabetical", "naming", "schema", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/raw.py#L10-L63
train
208,308
log2timeline/dfvfs
dfvfs/lib/raw.py
_RawGlobPathSpecWithNumericSchema
def _RawGlobPathSpecWithNumericSchema( file_system, parent_path_spec, segment_format, location, segment_number): """Globs for path specifications according to a numeric naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format (str): naming schema of the segment file location. location (str): the base segment file location string. segment_number (int): first segment number. Returns: list[PathSpec]: path specifications that match the glob. """ segment_files = [] while True: segment_location = segment_format.format(location, segment_number) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec) kwargs['location'] = segment_location if parent_path_spec.parent is not None: kwargs['parent'] = parent_path_spec.parent segment_path_spec = path_spec_factory.Factory.NewPathSpec( parent_path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(segment_path_spec): break segment_files.append(segment_path_spec) segment_number += 1 return segment_files
python
def _RawGlobPathSpecWithNumericSchema( file_system, parent_path_spec, segment_format, location, segment_number): """Globs for path specifications according to a numeric naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format (str): naming schema of the segment file location. location (str): the base segment file location string. segment_number (int): first segment number. Returns: list[PathSpec]: path specifications that match the glob. """ segment_files = [] while True: segment_location = segment_format.format(location, segment_number) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec) kwargs['location'] = segment_location if parent_path_spec.parent is not None: kwargs['parent'] = parent_path_spec.parent segment_path_spec = path_spec_factory.Factory.NewPathSpec( parent_path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(segment_path_spec): break segment_files.append(segment_path_spec) segment_number += 1 return segment_files
[ "def", "_RawGlobPathSpecWithNumericSchema", "(", "file_system", ",", "parent_path_spec", ",", "segment_format", ",", "location", ",", "segment_number", ")", ":", "segment_files", "=", "[", "]", "while", "True", ":", "segment_location", "=", "segment_format", ".", "f...
Globs for path specifications according to a numeric naming schema. Args: file_system (FileSystem): file system. parent_path_spec (PathSpec): parent path specification. segment_format (str): naming schema of the segment file location. location (str): the base segment file location string. segment_number (int): first segment number. Returns: list[PathSpec]: path specifications that match the glob.
[ "Globs", "for", "path", "specifications", "according", "to", "a", "numeric", "naming", "schema", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/raw.py#L66-L104
train
208,309
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanNode.GetSubNodeByLocation
def GetSubNodeByLocation(self, location): """Retrieves a sub scan node based on the location. Args: location (str): location that should match the location of the path specification of a sub scan node. Returns: SourceScanNode: sub scan node or None if not available. """ for sub_node in self.sub_nodes: sub_node_location = getattr(sub_node.path_spec, 'location', None) if location == sub_node_location: return sub_node return None
python
def GetSubNodeByLocation(self, location): """Retrieves a sub scan node based on the location. Args: location (str): location that should match the location of the path specification of a sub scan node. Returns: SourceScanNode: sub scan node or None if not available. """ for sub_node in self.sub_nodes: sub_node_location = getattr(sub_node.path_spec, 'location', None) if location == sub_node_location: return sub_node return None
[ "def", "GetSubNodeByLocation", "(", "self", ",", "location", ")", ":", "for", "sub_node", "in", "self", ".", "sub_nodes", ":", "sub_node_location", "=", "getattr", "(", "sub_node", ".", "path_spec", ",", "'location'", ",", "None", ")", "if", "location", "=="...
Retrieves a sub scan node based on the location. Args: location (str): location that should match the location of the path specification of a sub scan node. Returns: SourceScanNode: sub scan node or None if not available.
[ "Retrieves", "a", "sub", "scan", "node", "based", "on", "the", "location", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L51-L66
train
208,310
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanNode.GetUnscannedSubNode
def GetUnscannedSubNode(self): """Retrieves the first unscanned sub node. Returns: SourceScanNode: sub scan node or None if not available. """ if not self.sub_nodes and not self.scanned: return self for sub_node in self.sub_nodes: result = sub_node.GetUnscannedSubNode() if result: return result return None
python
def GetUnscannedSubNode(self): """Retrieves the first unscanned sub node. Returns: SourceScanNode: sub scan node or None if not available. """ if not self.sub_nodes and not self.scanned: return self for sub_node in self.sub_nodes: result = sub_node.GetUnscannedSubNode() if result: return result return None
[ "def", "GetUnscannedSubNode", "(", "self", ")", ":", "if", "not", "self", ".", "sub_nodes", "and", "not", "self", ".", "scanned", ":", "return", "self", "for", "sub_node", "in", "self", ".", "sub_nodes", ":", "result", "=", "sub_node", ".", "GetUnscannedSu...
Retrieves the first unscanned sub node. Returns: SourceScanNode: sub scan node or None if not available.
[ "Retrieves", "the", "first", "unscanned", "sub", "node", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L68-L82
train
208,311
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScannerContext.AddScanNode
def AddScanNode(self, path_spec, parent_scan_node): """Adds a scan node for a certain path specification. Args: path_spec (PathSpec): path specification. parent_scan_node (SourceScanNode): parent scan node or None. Returns: SourceScanNode: scan node. Raises: KeyError: if the scan node already exists. RuntimeError: if the parent scan node is not present. """ scan_node = self._scan_nodes.get(path_spec, None) if scan_node: raise KeyError('Scan node already exists.') scan_node = SourceScanNode(path_spec) if parent_scan_node: if parent_scan_node.path_spec not in self._scan_nodes: raise RuntimeError('Parent scan node not present.') scan_node.parent_node = parent_scan_node parent_scan_node.sub_nodes.append(scan_node) if not self._root_path_spec: self._root_path_spec = path_spec self._scan_nodes[path_spec] = scan_node if path_spec.IsFileSystem(): self._file_system_scan_nodes[path_spec] = scan_node self.updated = True return scan_node
python
def AddScanNode(self, path_spec, parent_scan_node): """Adds a scan node for a certain path specification. Args: path_spec (PathSpec): path specification. parent_scan_node (SourceScanNode): parent scan node or None. Returns: SourceScanNode: scan node. Raises: KeyError: if the scan node already exists. RuntimeError: if the parent scan node is not present. """ scan_node = self._scan_nodes.get(path_spec, None) if scan_node: raise KeyError('Scan node already exists.') scan_node = SourceScanNode(path_spec) if parent_scan_node: if parent_scan_node.path_spec not in self._scan_nodes: raise RuntimeError('Parent scan node not present.') scan_node.parent_node = parent_scan_node parent_scan_node.sub_nodes.append(scan_node) if not self._root_path_spec: self._root_path_spec = path_spec self._scan_nodes[path_spec] = scan_node if path_spec.IsFileSystem(): self._file_system_scan_nodes[path_spec] = scan_node self.updated = True return scan_node
[ "def", "AddScanNode", "(", "self", ",", "path_spec", ",", "parent_scan_node", ")", ":", "scan_node", "=", "self", ".", "_scan_nodes", ".", "get", "(", "path_spec", ",", "None", ")", "if", "scan_node", ":", "raise", "KeyError", "(", "'Scan node already exists.'...
Adds a scan node for a certain path specification. Args: path_spec (PathSpec): path specification. parent_scan_node (SourceScanNode): parent scan node or None. Returns: SourceScanNode: scan node. Raises: KeyError: if the scan node already exists. RuntimeError: if the parent scan node is not present.
[ "Adds", "a", "scan", "node", "for", "a", "certain", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L156-L190
train
208,312
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScannerContext.GetUnscannedScanNode
def GetUnscannedScanNode(self): """Retrieves the first unscanned scan node. Returns: SourceScanNode: scan node or None if not available. """ root_scan_node = self._scan_nodes.get(self._root_path_spec, None) if not root_scan_node or not root_scan_node.scanned: return root_scan_node return root_scan_node.GetUnscannedSubNode()
python
def GetUnscannedScanNode(self): """Retrieves the first unscanned scan node. Returns: SourceScanNode: scan node or None if not available. """ root_scan_node = self._scan_nodes.get(self._root_path_spec, None) if not root_scan_node or not root_scan_node.scanned: return root_scan_node return root_scan_node.GetUnscannedSubNode()
[ "def", "GetUnscannedScanNode", "(", "self", ")", ":", "root_scan_node", "=", "self", ".", "_scan_nodes", ".", "get", "(", "self", ".", "_root_path_spec", ",", "None", ")", "if", "not", "root_scan_node", "or", "not", "root_scan_node", ".", "scanned", ":", "re...
Retrieves the first unscanned scan node. Returns: SourceScanNode: scan node or None if not available.
[ "Retrieves", "the", "first", "unscanned", "scan", "node", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L211-L221
train
208,313
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScannerContext.LockScanNode
def LockScanNode(self, path_spec): """Marks a scan node as locked. Args: path_spec (PathSpec): path specification. Raises: KeyError: if the scan node does not exists. """ scan_node = self._scan_nodes.get(path_spec, None) if not scan_node: raise KeyError('Scan node does not exist.') self._locked_scan_nodes[path_spec] = scan_node
python
def LockScanNode(self, path_spec): """Marks a scan node as locked. Args: path_spec (PathSpec): path specification. Raises: KeyError: if the scan node does not exists. """ scan_node = self._scan_nodes.get(path_spec, None) if not scan_node: raise KeyError('Scan node does not exist.') self._locked_scan_nodes[path_spec] = scan_node
[ "def", "LockScanNode", "(", "self", ",", "path_spec", ")", ":", "scan_node", "=", "self", ".", "_scan_nodes", ".", "get", "(", "path_spec", ",", "None", ")", "if", "not", "scan_node", ":", "raise", "KeyError", "(", "'Scan node does not exist.'", ")", "self",...
Marks a scan node as locked. Args: path_spec (PathSpec): path specification. Raises: KeyError: if the scan node does not exists.
[ "Marks", "a", "scan", "node", "as", "locked", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L290-L303
train
208,314
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScannerContext.OpenSourcePath
def OpenSourcePath(self, source_path): """Opens the source path. Args: source_path (str): source path. """ source_path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_OS, location=source_path) self.AddScanNode(source_path_spec, None)
python
def OpenSourcePath(self, source_path): """Opens the source path. Args: source_path (str): source path. """ source_path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_OS, location=source_path) self.AddScanNode(source_path_spec, None)
[ "def", "OpenSourcePath", "(", "self", ",", "source_path", ")", ":", "source_path_spec", "=", "path_spec_factory", ".", "Factory", ".", "NewPathSpec", "(", "definitions", ".", "TYPE_INDICATOR_OS", ",", "location", "=", "source_path", ")", "self", ".", "AddScanNode"...
Opens the source path. Args: source_path (str): source path.
[ "Opens", "the", "source", "path", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L305-L314
train
208,315
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScannerContext.RemoveScanNode
def RemoveScanNode(self, path_spec): """Removes a scan node of a certain path specification. Args: path_spec (PathSpec): path specification. Returns: SourceScanNode: parent scan node or None if not available. Raises: RuntimeError: if the scan node has sub nodes. """ scan_node = self._scan_nodes.get(path_spec, None) if not scan_node: return None if scan_node.sub_nodes: raise RuntimeError('Scan node has sub nodes.') parent_scan_node = scan_node.parent_node if parent_scan_node: parent_scan_node.sub_nodes.remove(scan_node) if path_spec == self._root_path_spec: self._root_path_spec = None del self._scan_nodes[path_spec] if path_spec.IsFileSystem(): del self._file_system_scan_nodes[path_spec] return parent_scan_node
python
def RemoveScanNode(self, path_spec): """Removes a scan node of a certain path specification. Args: path_spec (PathSpec): path specification. Returns: SourceScanNode: parent scan node or None if not available. Raises: RuntimeError: if the scan node has sub nodes. """ scan_node = self._scan_nodes.get(path_spec, None) if not scan_node: return None if scan_node.sub_nodes: raise RuntimeError('Scan node has sub nodes.') parent_scan_node = scan_node.parent_node if parent_scan_node: parent_scan_node.sub_nodes.remove(scan_node) if path_spec == self._root_path_spec: self._root_path_spec = None del self._scan_nodes[path_spec] if path_spec.IsFileSystem(): del self._file_system_scan_nodes[path_spec] return parent_scan_node
[ "def", "RemoveScanNode", "(", "self", ",", "path_spec", ")", ":", "scan_node", "=", "self", ".", "_scan_nodes", ".", "get", "(", "path_spec", ",", "None", ")", "if", "not", "scan_node", ":", "return", "None", "if", "scan_node", ".", "sub_nodes", ":", "ra...
Removes a scan node of a certain path specification. Args: path_spec (PathSpec): path specification. Returns: SourceScanNode: parent scan node or None if not available. Raises: RuntimeError: if the scan node has sub nodes.
[ "Removes", "a", "scan", "node", "of", "a", "certain", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L316-L346
train
208,316
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScannerContext.UnlockScanNode
def UnlockScanNode(self, path_spec): """Marks a scan node as unlocked. Args: path_spec (PathSpec): path specification. Raises: KeyError: if the scan node does not exists or is not locked. """ if not self.HasScanNode(path_spec): raise KeyError('Scan node does not exist.') if path_spec not in self._locked_scan_nodes: raise KeyError('Scan node is not locked.') del self._locked_scan_nodes[path_spec] # Scan a node again after it has been unlocked. self._scan_nodes[path_spec].scanned = False
python
def UnlockScanNode(self, path_spec): """Marks a scan node as unlocked. Args: path_spec (PathSpec): path specification. Raises: KeyError: if the scan node does not exists or is not locked. """ if not self.HasScanNode(path_spec): raise KeyError('Scan node does not exist.') if path_spec not in self._locked_scan_nodes: raise KeyError('Scan node is not locked.') del self._locked_scan_nodes[path_spec] # Scan a node again after it has been unlocked. self._scan_nodes[path_spec].scanned = False
[ "def", "UnlockScanNode", "(", "self", ",", "path_spec", ")", ":", "if", "not", "self", ".", "HasScanNode", "(", "path_spec", ")", ":", "raise", "KeyError", "(", "'Scan node does not exist.'", ")", "if", "path_spec", "not", "in", "self", ".", "_locked_scan_node...
Marks a scan node as unlocked. Args: path_spec (PathSpec): path specification. Raises: KeyError: if the scan node does not exists or is not locked.
[ "Marks", "a", "scan", "node", "as", "unlocked", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L357-L375
train
208,317
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner._ScanNode
def _ScanNode(self, scan_context, scan_node, auto_recurse=True): """Scans a node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. Raises: BackEndError: if the source cannot be scanned. ValueError: if the scan context or scan node is invalid. """ if not scan_context: raise ValueError('Invalid scan context.') if not scan_node: raise ValueError('Invalid scan node.') scan_path_spec = scan_node.path_spec system_level_file_entry = None if scan_node.IsSystemLevel(): system_level_file_entry = resolver.Resolver.OpenFileEntry( scan_node.path_spec, resolver_context=self._resolver_context) if system_level_file_entry is None: raise errors.BackEndError('Unable to open file entry.') if system_level_file_entry.IsDirectory(): scan_context.SetSourceType(definitions.SOURCE_TYPE_DIRECTORY) return source_path_spec = self.ScanForStorageMediaImage(scan_node.path_spec) if source_path_spec: scan_node.scanned = True scan_node = scan_context.AddScanNode(source_path_spec, scan_node) if system_level_file_entry.IsDevice(): source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE else: source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE scan_context.SetSourceType(source_type) if not auto_recurse: return # In case we did not find a storage media image type we keep looking # since not all RAW storage media image naming schemas are known and # its type can only detected by its content. source_path_spec = None while True: if scan_node.IsFileSystem(): # No need to scan a file systems scan node for volume systems. break if scan_node.SupportsEncryption(): self._ScanEncryptedVolumeNode(scan_context, scan_node) if scan_context.IsLockedScanNode(scan_node.path_spec): # Scan node is locked, such as an encrypted volume, and we cannot # scan it for a volume system. break source_path_spec = self.ScanForVolumeSystem(scan_node.path_spec) if not source_path_spec: # No volume system found continue with a file system scan. break if not scan_context.HasScanNode(source_path_spec): scan_node.scanned = True scan_node = scan_context.AddScanNode(source_path_spec, scan_node) if system_level_file_entry and system_level_file_entry.IsDevice(): source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE else: source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE scan_context.SetSourceType(source_type) if scan_node.IsVolumeSystemRoot(): self._ScanVolumeSystemRootNode( scan_context, scan_node, auto_recurse=auto_recurse) # We already have already scanned for the file systems. return if not auto_recurse and scan_context.updated: return # Nothing new found. if not scan_context.updated: break # In case we did not find a volume system type we keep looking # since we could be dealing with a storage media image that contains # a single volume. # No need to scan the root of a volume system for a file system. if scan_node.IsVolumeSystemRoot(): pass elif scan_context.IsLockedScanNode(scan_node.path_spec): # Scan node is locked, such as an encrypted volume, and we cannot # scan it for a file system. pass elif (scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW and auto_recurse and scan_node.path_spec != scan_path_spec): # Since scanning for file systems in VSS snapshot volumes can # be expensive we only do this when explicitly asked for. pass elif not scan_node.IsFileSystem(): source_path_spec = self.ScanForFileSystem(scan_node.path_spec) if not source_path_spec: # Since RAW storage media image can only be determined by naming schema # we could have single file that is not a RAW storage media image yet # matches the naming schema. if scan_node.path_spec.type_indicator == definitions.TYPE_INDICATOR_RAW: scan_node = scan_context.RemoveScanNode(scan_node.path_spec) # Make sure to override the previously assigned source type. scan_context.source_type = definitions.SOURCE_TYPE_FILE else: scan_context.SetSourceType(definitions.SOURCE_TYPE_FILE) elif not scan_context.HasScanNode(source_path_spec): scan_node.scanned = True scan_node = scan_context.AddScanNode(source_path_spec, scan_node) if system_level_file_entry and system_level_file_entry.IsDevice(): source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE else: source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE scan_context.SetSourceType(source_type) # If all scans failed mark the scan node as scanned so we do not scan it # again. if not scan_node.scanned: scan_node.scanned = True
python
def _ScanNode(self, scan_context, scan_node, auto_recurse=True): """Scans a node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. Raises: BackEndError: if the source cannot be scanned. ValueError: if the scan context or scan node is invalid. """ if not scan_context: raise ValueError('Invalid scan context.') if not scan_node: raise ValueError('Invalid scan node.') scan_path_spec = scan_node.path_spec system_level_file_entry = None if scan_node.IsSystemLevel(): system_level_file_entry = resolver.Resolver.OpenFileEntry( scan_node.path_spec, resolver_context=self._resolver_context) if system_level_file_entry is None: raise errors.BackEndError('Unable to open file entry.') if system_level_file_entry.IsDirectory(): scan_context.SetSourceType(definitions.SOURCE_TYPE_DIRECTORY) return source_path_spec = self.ScanForStorageMediaImage(scan_node.path_spec) if source_path_spec: scan_node.scanned = True scan_node = scan_context.AddScanNode(source_path_spec, scan_node) if system_level_file_entry.IsDevice(): source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE else: source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE scan_context.SetSourceType(source_type) if not auto_recurse: return # In case we did not find a storage media image type we keep looking # since not all RAW storage media image naming schemas are known and # its type can only detected by its content. source_path_spec = None while True: if scan_node.IsFileSystem(): # No need to scan a file systems scan node for volume systems. break if scan_node.SupportsEncryption(): self._ScanEncryptedVolumeNode(scan_context, scan_node) if scan_context.IsLockedScanNode(scan_node.path_spec): # Scan node is locked, such as an encrypted volume, and we cannot # scan it for a volume system. break source_path_spec = self.ScanForVolumeSystem(scan_node.path_spec) if not source_path_spec: # No volume system found continue with a file system scan. break if not scan_context.HasScanNode(source_path_spec): scan_node.scanned = True scan_node = scan_context.AddScanNode(source_path_spec, scan_node) if system_level_file_entry and system_level_file_entry.IsDevice(): source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE else: source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE scan_context.SetSourceType(source_type) if scan_node.IsVolumeSystemRoot(): self._ScanVolumeSystemRootNode( scan_context, scan_node, auto_recurse=auto_recurse) # We already have already scanned for the file systems. return if not auto_recurse and scan_context.updated: return # Nothing new found. if not scan_context.updated: break # In case we did not find a volume system type we keep looking # since we could be dealing with a storage media image that contains # a single volume. # No need to scan the root of a volume system for a file system. if scan_node.IsVolumeSystemRoot(): pass elif scan_context.IsLockedScanNode(scan_node.path_spec): # Scan node is locked, such as an encrypted volume, and we cannot # scan it for a file system. pass elif (scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW and auto_recurse and scan_node.path_spec != scan_path_spec): # Since scanning for file systems in VSS snapshot volumes can # be expensive we only do this when explicitly asked for. pass elif not scan_node.IsFileSystem(): source_path_spec = self.ScanForFileSystem(scan_node.path_spec) if not source_path_spec: # Since RAW storage media image can only be determined by naming schema # we could have single file that is not a RAW storage media image yet # matches the naming schema. if scan_node.path_spec.type_indicator == definitions.TYPE_INDICATOR_RAW: scan_node = scan_context.RemoveScanNode(scan_node.path_spec) # Make sure to override the previously assigned source type. scan_context.source_type = definitions.SOURCE_TYPE_FILE else: scan_context.SetSourceType(definitions.SOURCE_TYPE_FILE) elif not scan_context.HasScanNode(source_path_spec): scan_node.scanned = True scan_node = scan_context.AddScanNode(source_path_spec, scan_node) if system_level_file_entry and system_level_file_entry.IsDevice(): source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE else: source_type = definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE scan_context.SetSourceType(source_type) # If all scans failed mark the scan node as scanned so we do not scan it # again. if not scan_node.scanned: scan_node.scanned = True
[ "def", "_ScanNode", "(", "self", ",", "scan_context", ",", "scan_node", ",", "auto_recurse", "=", "True", ")", ":", "if", "not", "scan_context", ":", "raise", "ValueError", "(", "'Invalid scan context.'", ")", "if", "not", "scan_node", ":", "raise", "ValueErro...
Scans a node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. Raises: BackEndError: if the source cannot be scanned. ValueError: if the scan context or scan node is invalid.
[ "Scans", "a", "node", "for", "supported", "formats", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L395-L538
train
208,318
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner._ScanEncryptedVolumeNode
def _ScanEncryptedVolumeNode(self, scan_context, scan_node): """Scans an encrypted volume node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. Raises: BackEndError: if the scan node cannot be unlocked. ValueError: if the scan context or scan node is invalid. """ if scan_node.type_indicator == definitions.TYPE_INDICATOR_APFS_CONTAINER: # TODO: consider changes this when upstream changes have been made. # Currently pyfsapfs does not support reading from a volume as a device. # Also see: https://github.com/log2timeline/dfvfs/issues/332 container_file_entry = resolver.Resolver.OpenFileEntry( scan_node.path_spec, resolver_context=self._resolver_context) fsapfs_volume = container_file_entry.GetAPFSVolume() # TODO: unlocking the volume multiple times is inefficient cache volume # object in scan node and use is_locked = fsapfs_volume.is_locked() try: is_locked = not apfs_helper.APFSUnlockVolume( fsapfs_volume, scan_node.path_spec, resolver.Resolver.key_chain) except IOError as exception: raise errors.BackEndError( 'Unable to unlock APFS volume with error: {0!s}'.format(exception)) else: file_object = resolver.Resolver.OpenFileObject( scan_node.path_spec, resolver_context=self._resolver_context) is_locked = not file_object or file_object.is_locked file_object.close() if is_locked: scan_context.LockScanNode(scan_node.path_spec) # For BitLocker To Go add a scan node for the unencrypted part of # the volume. if scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE: path_spec = self.ScanForFileSystem(scan_node.path_spec.parent) if path_spec: scan_context.AddScanNode(path_spec, scan_node.parent_node)
python
def _ScanEncryptedVolumeNode(self, scan_context, scan_node): """Scans an encrypted volume node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. Raises: BackEndError: if the scan node cannot be unlocked. ValueError: if the scan context or scan node is invalid. """ if scan_node.type_indicator == definitions.TYPE_INDICATOR_APFS_CONTAINER: # TODO: consider changes this when upstream changes have been made. # Currently pyfsapfs does not support reading from a volume as a device. # Also see: https://github.com/log2timeline/dfvfs/issues/332 container_file_entry = resolver.Resolver.OpenFileEntry( scan_node.path_spec, resolver_context=self._resolver_context) fsapfs_volume = container_file_entry.GetAPFSVolume() # TODO: unlocking the volume multiple times is inefficient cache volume # object in scan node and use is_locked = fsapfs_volume.is_locked() try: is_locked = not apfs_helper.APFSUnlockVolume( fsapfs_volume, scan_node.path_spec, resolver.Resolver.key_chain) except IOError as exception: raise errors.BackEndError( 'Unable to unlock APFS volume with error: {0!s}'.format(exception)) else: file_object = resolver.Resolver.OpenFileObject( scan_node.path_spec, resolver_context=self._resolver_context) is_locked = not file_object or file_object.is_locked file_object.close() if is_locked: scan_context.LockScanNode(scan_node.path_spec) # For BitLocker To Go add a scan node for the unencrypted part of # the volume. if scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE: path_spec = self.ScanForFileSystem(scan_node.path_spec.parent) if path_spec: scan_context.AddScanNode(path_spec, scan_node.parent_node)
[ "def", "_ScanEncryptedVolumeNode", "(", "self", ",", "scan_context", ",", "scan_node", ")", ":", "if", "scan_node", ".", "type_indicator", "==", "definitions", ".", "TYPE_INDICATOR_APFS_CONTAINER", ":", "# TODO: consider changes this when upstream changes have been made.", "#...
Scans an encrypted volume node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. Raises: BackEndError: if the scan node cannot be unlocked. ValueError: if the scan context or scan node is invalid.
[ "Scans", "an", "encrypted", "volume", "node", "for", "supported", "formats", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L540-L582
train
208,319
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner._ScanVolumeSystemRootNode
def _ScanVolumeSystemRootNode( self, scan_context, scan_node, auto_recurse=True): """Scans a volume system root node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. Raises: ValueError: if the scan context or scan node is invalid. """ if scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: # For VSS add a scan node for the current volume. path_spec = self.ScanForFileSystem(scan_node.path_spec.parent) if path_spec: scan_context.AddScanNode(path_spec, scan_node.parent_node) # Determine the path specifications of the sub file entries. file_entry = resolver.Resolver.OpenFileEntry( scan_node.path_spec, resolver_context=self._resolver_context) for sub_file_entry in file_entry.sub_file_entries: sub_scan_node = scan_context.AddScanNode( sub_file_entry.path_spec, scan_node) if scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: # Since scanning for file systems in VSS snapshot volumes can # be expensive we only do this when explicitly asked for. continue if auto_recurse or not scan_context.updated: self._ScanNode(scan_context, sub_scan_node, auto_recurse=auto_recurse)
python
def _ScanVolumeSystemRootNode( self, scan_context, scan_node, auto_recurse=True): """Scans a volume system root node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. Raises: ValueError: if the scan context or scan node is invalid. """ if scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: # For VSS add a scan node for the current volume. path_spec = self.ScanForFileSystem(scan_node.path_spec.parent) if path_spec: scan_context.AddScanNode(path_spec, scan_node.parent_node) # Determine the path specifications of the sub file entries. file_entry = resolver.Resolver.OpenFileEntry( scan_node.path_spec, resolver_context=self._resolver_context) for sub_file_entry in file_entry.sub_file_entries: sub_scan_node = scan_context.AddScanNode( sub_file_entry.path_spec, scan_node) if scan_node.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: # Since scanning for file systems in VSS snapshot volumes can # be expensive we only do this when explicitly asked for. continue if auto_recurse or not scan_context.updated: self._ScanNode(scan_context, sub_scan_node, auto_recurse=auto_recurse)
[ "def", "_ScanVolumeSystemRootNode", "(", "self", ",", "scan_context", ",", "scan_node", ",", "auto_recurse", "=", "True", ")", ":", "if", "scan_node", ".", "type_indicator", "==", "definitions", ".", "TYPE_INDICATOR_VSHADOW", ":", "# For VSS add a scan node for the curr...
Scans a volume system root node for supported formats. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): source scan node. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. Raises: ValueError: if the scan context or scan node is invalid.
[ "Scans", "a", "volume", "system", "root", "node", "for", "supported", "formats", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L584-L617
train
208,320
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner.GetVolumeIdentifiers
def GetVolumeIdentifiers(self, volume_system): """Retrieves the volume identifiers. Args: volume_system (VolumeSystem): volume system. Returns: list[str]: sorted volume identifiers. """ volume_identifiers = [] for volume in volume_system.volumes: volume_identifier = getattr(volume, 'identifier', None) if volume_identifier: volume_identifiers.append(volume_identifier) return sorted(volume_identifiers)
python
def GetVolumeIdentifiers(self, volume_system): """Retrieves the volume identifiers. Args: volume_system (VolumeSystem): volume system. Returns: list[str]: sorted volume identifiers. """ volume_identifiers = [] for volume in volume_system.volumes: volume_identifier = getattr(volume, 'identifier', None) if volume_identifier: volume_identifiers.append(volume_identifier) return sorted(volume_identifiers)
[ "def", "GetVolumeIdentifiers", "(", "self", ",", "volume_system", ")", ":", "volume_identifiers", "=", "[", "]", "for", "volume", "in", "volume_system", ".", "volumes", ":", "volume_identifier", "=", "getattr", "(", "volume", ",", "'identifier'", ",", "None", ...
Retrieves the volume identifiers. Args: volume_system (VolumeSystem): volume system. Returns: list[str]: sorted volume identifiers.
[ "Retrieves", "the", "volume", "identifiers", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L619-L634
train
208,321
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner.Scan
def Scan(self, scan_context, auto_recurse=True, scan_path_spec=None): """Scans for supported formats. Args: scan_context (SourceScannerContext): source scanner context. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. scan_path_spec (Optional[PathSpec]): path specification to indicate where the source scanner should continue scanning, where None indicates the scanner will start with the sources. Raises: ValueError: if the scan context is invalid. """ if not scan_context: raise ValueError('Invalid scan context.') scan_context.updated = False if scan_path_spec: scan_node = scan_context.GetScanNode(scan_path_spec) else: scan_node = scan_context.GetUnscannedScanNode() if scan_node: self._ScanNode(scan_context, scan_node, auto_recurse=auto_recurse)
python
def Scan(self, scan_context, auto_recurse=True, scan_path_spec=None): """Scans for supported formats. Args: scan_context (SourceScannerContext): source scanner context. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. scan_path_spec (Optional[PathSpec]): path specification to indicate where the source scanner should continue scanning, where None indicates the scanner will start with the sources. Raises: ValueError: if the scan context is invalid. """ if not scan_context: raise ValueError('Invalid scan context.') scan_context.updated = False if scan_path_spec: scan_node = scan_context.GetScanNode(scan_path_spec) else: scan_node = scan_context.GetUnscannedScanNode() if scan_node: self._ScanNode(scan_context, scan_node, auto_recurse=auto_recurse)
[ "def", "Scan", "(", "self", ",", "scan_context", ",", "auto_recurse", "=", "True", ",", "scan_path_spec", "=", "None", ")", ":", "if", "not", "scan_context", ":", "raise", "ValueError", "(", "'Invalid scan context.'", ")", "scan_context", ".", "updated", "=", ...
Scans for supported formats. Args: scan_context (SourceScannerContext): source scanner context. auto_recurse (Optional[bool]): True if the scan should automatically recurse as far as possible. scan_path_spec (Optional[PathSpec]): path specification to indicate where the source scanner should continue scanning, where None indicates the scanner will start with the sources. Raises: ValueError: if the scan context is invalid.
[ "Scans", "for", "supported", "formats", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L636-L662
train
208,322
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner.ScanForFileSystem
def ScanForFileSystem(self, source_path_spec): """Scans the path specification for a supported file system format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: file system path specification or None if no supported file system type was found. Raises: BackEndError: if the source cannot be scanned or more than one file system type is found. """ if source_path_spec.type_indicator == ( definitions.TYPE_INDICATOR_APFS_CONTAINER): # TODO: consider changes this when upstream changes have been made. # Currently pyfsapfs does not support reading from a volume as a device. # Also see: https://github.com/log2timeline/dfvfs/issues/332 return path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_APFS, location='/', parent=source_path_spec) try: type_indicators = analyzer.Analyzer.GetFileSystemTypeIndicators( source_path_spec, resolver_context=self._resolver_context) except RuntimeError as exception: raise errors.BackEndError(( 'Unable to process source path specification with error: ' '{0!s}').format(exception)) if not type_indicators: return None type_indicator = type_indicators[0] if len(type_indicators) > 1: if definitions.PREFERRED_NTFS_BACK_END not in type_indicators: raise errors.BackEndError( 'Unsupported source found more than one file system types.') type_indicator = definitions.PREFERRED_NTFS_BACK_END # TODO: determine root location from file system or path specification. if type_indicator == definitions.TYPE_INDICATOR_NTFS: root_location = '\\' else: root_location = '/' file_system_path_spec = path_spec_factory.Factory.NewPathSpec( type_indicator, location=root_location, parent=source_path_spec) if type_indicator == definitions.TYPE_INDICATOR_TSK: # Check if the file system can be opened since the file system by # signature detection results in false positives. try: file_system = resolver.Resolver.OpenFileSystem( file_system_path_spec, resolver_context=self._resolver_context) file_system.Close() except errors.BackEndError: file_system_path_spec = None return file_system_path_spec
python
def ScanForFileSystem(self, source_path_spec): """Scans the path specification for a supported file system format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: file system path specification or None if no supported file system type was found. Raises: BackEndError: if the source cannot be scanned or more than one file system type is found. """ if source_path_spec.type_indicator == ( definitions.TYPE_INDICATOR_APFS_CONTAINER): # TODO: consider changes this when upstream changes have been made. # Currently pyfsapfs does not support reading from a volume as a device. # Also see: https://github.com/log2timeline/dfvfs/issues/332 return path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_APFS, location='/', parent=source_path_spec) try: type_indicators = analyzer.Analyzer.GetFileSystemTypeIndicators( source_path_spec, resolver_context=self._resolver_context) except RuntimeError as exception: raise errors.BackEndError(( 'Unable to process source path specification with error: ' '{0!s}').format(exception)) if not type_indicators: return None type_indicator = type_indicators[0] if len(type_indicators) > 1: if definitions.PREFERRED_NTFS_BACK_END not in type_indicators: raise errors.BackEndError( 'Unsupported source found more than one file system types.') type_indicator = definitions.PREFERRED_NTFS_BACK_END # TODO: determine root location from file system or path specification. if type_indicator == definitions.TYPE_INDICATOR_NTFS: root_location = '\\' else: root_location = '/' file_system_path_spec = path_spec_factory.Factory.NewPathSpec( type_indicator, location=root_location, parent=source_path_spec) if type_indicator == definitions.TYPE_INDICATOR_TSK: # Check if the file system can be opened since the file system by # signature detection results in false positives. try: file_system = resolver.Resolver.OpenFileSystem( file_system_path_spec, resolver_context=self._resolver_context) file_system.Close() except errors.BackEndError: file_system_path_spec = None return file_system_path_spec
[ "def", "ScanForFileSystem", "(", "self", ",", "source_path_spec", ")", ":", "if", "source_path_spec", ".", "type_indicator", "==", "(", "definitions", ".", "TYPE_INDICATOR_APFS_CONTAINER", ")", ":", "# TODO: consider changes this when upstream changes have been made.", "# Cur...
Scans the path specification for a supported file system format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: file system path specification or None if no supported file system type was found. Raises: BackEndError: if the source cannot be scanned or more than one file system type is found.
[ "Scans", "the", "path", "specification", "for", "a", "supported", "file", "system", "format", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L664-L725
train
208,323
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner.ScanForStorageMediaImage
def ScanForStorageMediaImage(self, source_path_spec): """Scans the path specification for a supported storage media image format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: storage media image path specification or None if no supported storage media image type was found. Raises: BackEndError: if the source cannot be scanned or more than one storage media image type is found. """ try: type_indicators = analyzer.Analyzer.GetStorageMediaImageTypeIndicators( source_path_spec, resolver_context=self._resolver_context) except RuntimeError as exception: raise errors.BackEndError(( 'Unable to process source path specification with error: ' '{0!s}').format(exception)) if not type_indicators: # The RAW storage media image type cannot be detected based on # a signature so we try to detect it based on common file naming schemas. file_system = resolver.Resolver.OpenFileSystem( source_path_spec, resolver_context=self._resolver_context) raw_path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_RAW, parent=source_path_spec) try: # The RAW glob function will raise a PathSpecError if the path # specification is unsuitable for globbing. glob_results = raw.RawGlobPathSpec(file_system, raw_path_spec) except errors.PathSpecError: glob_results = None file_system.Close() if not glob_results: return None return raw_path_spec if len(type_indicators) > 1: raise errors.BackEndError( 'Unsupported source found more than one storage media image types.') return path_spec_factory.Factory.NewPathSpec( type_indicators[0], parent=source_path_spec)
python
def ScanForStorageMediaImage(self, source_path_spec): """Scans the path specification for a supported storage media image format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: storage media image path specification or None if no supported storage media image type was found. Raises: BackEndError: if the source cannot be scanned or more than one storage media image type is found. """ try: type_indicators = analyzer.Analyzer.GetStorageMediaImageTypeIndicators( source_path_spec, resolver_context=self._resolver_context) except RuntimeError as exception: raise errors.BackEndError(( 'Unable to process source path specification with error: ' '{0!s}').format(exception)) if not type_indicators: # The RAW storage media image type cannot be detected based on # a signature so we try to detect it based on common file naming schemas. file_system = resolver.Resolver.OpenFileSystem( source_path_spec, resolver_context=self._resolver_context) raw_path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_RAW, parent=source_path_spec) try: # The RAW glob function will raise a PathSpecError if the path # specification is unsuitable for globbing. glob_results = raw.RawGlobPathSpec(file_system, raw_path_spec) except errors.PathSpecError: glob_results = None file_system.Close() if not glob_results: return None return raw_path_spec if len(type_indicators) > 1: raise errors.BackEndError( 'Unsupported source found more than one storage media image types.') return path_spec_factory.Factory.NewPathSpec( type_indicators[0], parent=source_path_spec)
[ "def", "ScanForStorageMediaImage", "(", "self", ",", "source_path_spec", ")", ":", "try", ":", "type_indicators", "=", "analyzer", ".", "Analyzer", ".", "GetStorageMediaImageTypeIndicators", "(", "source_path_spec", ",", "resolver_context", "=", "self", ".", "_resolve...
Scans the path specification for a supported storage media image format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: storage media image path specification or None if no supported storage media image type was found. Raises: BackEndError: if the source cannot be scanned or more than one storage media image type is found.
[ "Scans", "the", "path", "specification", "for", "a", "supported", "storage", "media", "image", "format", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L727-L776
train
208,324
log2timeline/dfvfs
dfvfs/helpers/source_scanner.py
SourceScanner.ScanForVolumeSystem
def ScanForVolumeSystem(self, source_path_spec): """Scans the path specification for a supported volume system format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: volume system path specification or None if no supported volume system type was found. Raises: BackEndError: if the source cannot be scanned or more than one volume system type is found. """ if source_path_spec.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: # It is technically possible to scan for VSS-in-VSS but makes no sense # to do so. return None if source_path_spec.IsVolumeSystemRoot(): return source_path_spec if source_path_spec.type_indicator == ( definitions.TYPE_INDICATOR_APFS_CONTAINER): # TODO: consider changes this when upstream changes have been made. # Currently pyfsapfs does not support reading from a volume as a device. # Also see: https://github.com/log2timeline/dfvfs/issues/332 return None try: type_indicators = analyzer.Analyzer.GetVolumeSystemTypeIndicators( source_path_spec, resolver_context=self._resolver_context) except (IOError, RuntimeError) as exception: raise errors.BackEndError(( 'Unable to process source path specification with error: ' '{0!s}').format(exception)) if not type_indicators: return None if len(type_indicators) > 1: raise errors.BackEndError( 'Unsupported source found more than one volume system types.') if (type_indicators[0] == definitions.TYPE_INDICATOR_TSK_PARTITION and source_path_spec.type_indicator in [ definitions.TYPE_INDICATOR_TSK_PARTITION]): return None if type_indicators[0] in definitions.VOLUME_SYSTEM_TYPE_INDICATORS: return path_spec_factory.Factory.NewPathSpec( type_indicators[0], location='/', parent=source_path_spec) return path_spec_factory.Factory.NewPathSpec( type_indicators[0], parent=source_path_spec)
python
def ScanForVolumeSystem(self, source_path_spec): """Scans the path specification for a supported volume system format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: volume system path specification or None if no supported volume system type was found. Raises: BackEndError: if the source cannot be scanned or more than one volume system type is found. """ if source_path_spec.type_indicator == definitions.TYPE_INDICATOR_VSHADOW: # It is technically possible to scan for VSS-in-VSS but makes no sense # to do so. return None if source_path_spec.IsVolumeSystemRoot(): return source_path_spec if source_path_spec.type_indicator == ( definitions.TYPE_INDICATOR_APFS_CONTAINER): # TODO: consider changes this when upstream changes have been made. # Currently pyfsapfs does not support reading from a volume as a device. # Also see: https://github.com/log2timeline/dfvfs/issues/332 return None try: type_indicators = analyzer.Analyzer.GetVolumeSystemTypeIndicators( source_path_spec, resolver_context=self._resolver_context) except (IOError, RuntimeError) as exception: raise errors.BackEndError(( 'Unable to process source path specification with error: ' '{0!s}').format(exception)) if not type_indicators: return None if len(type_indicators) > 1: raise errors.BackEndError( 'Unsupported source found more than one volume system types.') if (type_indicators[0] == definitions.TYPE_INDICATOR_TSK_PARTITION and source_path_spec.type_indicator in [ definitions.TYPE_INDICATOR_TSK_PARTITION]): return None if type_indicators[0] in definitions.VOLUME_SYSTEM_TYPE_INDICATORS: return path_spec_factory.Factory.NewPathSpec( type_indicators[0], location='/', parent=source_path_spec) return path_spec_factory.Factory.NewPathSpec( type_indicators[0], parent=source_path_spec)
[ "def", "ScanForVolumeSystem", "(", "self", ",", "source_path_spec", ")", ":", "if", "source_path_spec", ".", "type_indicator", "==", "definitions", ".", "TYPE_INDICATOR_VSHADOW", ":", "# It is technically possible to scan for VSS-in-VSS but makes no sense", "# to do so.", "retu...
Scans the path specification for a supported volume system format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: volume system path specification or None if no supported volume system type was found. Raises: BackEndError: if the source cannot be scanned or more than one volume system type is found.
[ "Scans", "the", "path", "specification", "for", "a", "supported", "volume", "system", "format", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/source_scanner.py#L778-L832
train
208,325
log2timeline/dfvfs
dfvfs/helpers/command_line.py
CLITabularTableView._WriteRow
def _WriteRow(self, output_writer, values, in_bold=False): """Writes a row of values aligned with the width to the output writer. Args: output_writer (CLIOutputWriter): output writer. values (list[object]): values. in_bold (Optional[bool]): True if the row should be written in bold. """ row_strings = [] for value_index, value_string in enumerate(values): padding_size = self._column_sizes[value_index] - len(value_string) padding_string = ' ' * padding_size row_strings.extend([value_string, padding_string]) row_strings.pop() row_strings = ''.join(row_strings) if in_bold and not win32console: # TODO: for win32console get current color and set intensity, # write the header separately then reset intensity. row_strings = '\x1b[1m{0:s}\x1b[0m'.format(row_strings) output_writer.Write('{0:s}\n'.format(row_strings))
python
def _WriteRow(self, output_writer, values, in_bold=False): """Writes a row of values aligned with the width to the output writer. Args: output_writer (CLIOutputWriter): output writer. values (list[object]): values. in_bold (Optional[bool]): True if the row should be written in bold. """ row_strings = [] for value_index, value_string in enumerate(values): padding_size = self._column_sizes[value_index] - len(value_string) padding_string = ' ' * padding_size row_strings.extend([value_string, padding_string]) row_strings.pop() row_strings = ''.join(row_strings) if in_bold and not win32console: # TODO: for win32console get current color and set intensity, # write the header separately then reset intensity. row_strings = '\x1b[1m{0:s}\x1b[0m'.format(row_strings) output_writer.Write('{0:s}\n'.format(row_strings))
[ "def", "_WriteRow", "(", "self", ",", "output_writer", ",", "values", ",", "in_bold", "=", "False", ")", ":", "row_strings", "=", "[", "]", "for", "value_index", ",", "value_string", "in", "enumerate", "(", "values", ")", ":", "padding_size", "=", "self", ...
Writes a row of values aligned with the width to the output writer. Args: output_writer (CLIOutputWriter): output writer. values (list[object]): values. in_bold (Optional[bool]): True if the row should be written in bold.
[ "Writes", "a", "row", "of", "values", "aligned", "with", "the", "width", "to", "the", "output", "writer", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/command_line.py#L213-L237
train
208,326
log2timeline/dfvfs
dfvfs/helpers/command_line.py
CLITabularTableView.Write
def Write(self, output_writer): """Writes the table to output writer. Args: output_writer (CLIOutputWriter): output writer. """ # Round up the column sizes to the nearest tab. for column_index, column_size in enumerate(self._column_sizes): column_size, _ = divmod(column_size, self._NUMBER_OF_SPACES_IN_TAB) column_size = (column_size + 1) * self._NUMBER_OF_SPACES_IN_TAB self._column_sizes[column_index] = column_size if self._columns: self._WriteRow(output_writer, self._columns, in_bold=True) for values in self._rows: self._WriteRow(output_writer, values)
python
def Write(self, output_writer): """Writes the table to output writer. Args: output_writer (CLIOutputWriter): output writer. """ # Round up the column sizes to the nearest tab. for column_index, column_size in enumerate(self._column_sizes): column_size, _ = divmod(column_size, self._NUMBER_OF_SPACES_IN_TAB) column_size = (column_size + 1) * self._NUMBER_OF_SPACES_IN_TAB self._column_sizes[column_index] = column_size if self._columns: self._WriteRow(output_writer, self._columns, in_bold=True) for values in self._rows: self._WriteRow(output_writer, values)
[ "def", "Write", "(", "self", ",", "output_writer", ")", ":", "# Round up the column sizes to the nearest tab.", "for", "column_index", ",", "column_size", "in", "enumerate", "(", "self", ".", "_column_sizes", ")", ":", "column_size", ",", "_", "=", "divmod", "(", ...
Writes the table to output writer. Args: output_writer (CLIOutputWriter): output writer.
[ "Writes", "the", "table", "to", "output", "writer", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/command_line.py#L268-L284
train
208,327
log2timeline/dfvfs
dfvfs/helpers/command_line.py
CLIVolumeScannerMediator.GetVSSStoreIdentifiers
def GetVSSStoreIdentifiers(self, volume_system, volume_identifiers): """Retrieves VSS store identifiers. This method can be used to prompt the user to provide VSS store identifiers. Args: volume_system (VShadowVolumeSystem): volume system. volume_identifiers (list[str]): volume identifiers including prefix. Returns: list[str]: selected volume identifiers including prefix or None. """ print_header = True while True: if print_header: self._PrintVSSStoreIdentifiersOverview( volume_system, volume_identifiers) print_header = False self._output_writer.Write('\n') lines = self._textwrapper.wrap(self._USER_PROMPT_VSS) self._output_writer.Write('\n'.join(lines)) self._output_writer.Write('\n\nVSS identifier(s): ') try: selected_volumes = self._ReadSelectedVolumes( volume_system, prefix='vss') if (not selected_volumes or not set(selected_volumes).difference(volume_identifiers)): break except ValueError: pass self._output_writer.Write('\n') lines = self._textwrapper.wrap( 'Unsupported VSS identifier(s), please try again or abort with ' 'Ctrl^C.') self._output_writer.Write('\n'.join(lines)) self._output_writer.Write('\n\n') return selected_volumes
python
def GetVSSStoreIdentifiers(self, volume_system, volume_identifiers): """Retrieves VSS store identifiers. This method can be used to prompt the user to provide VSS store identifiers. Args: volume_system (VShadowVolumeSystem): volume system. volume_identifiers (list[str]): volume identifiers including prefix. Returns: list[str]: selected volume identifiers including prefix or None. """ print_header = True while True: if print_header: self._PrintVSSStoreIdentifiersOverview( volume_system, volume_identifiers) print_header = False self._output_writer.Write('\n') lines = self._textwrapper.wrap(self._USER_PROMPT_VSS) self._output_writer.Write('\n'.join(lines)) self._output_writer.Write('\n\nVSS identifier(s): ') try: selected_volumes = self._ReadSelectedVolumes( volume_system, prefix='vss') if (not selected_volumes or not set(selected_volumes).difference(volume_identifiers)): break except ValueError: pass self._output_writer.Write('\n') lines = self._textwrapper.wrap( 'Unsupported VSS identifier(s), please try again or abort with ' 'Ctrl^C.') self._output_writer.Write('\n'.join(lines)) self._output_writer.Write('\n\n') return selected_volumes
[ "def", "GetVSSStoreIdentifiers", "(", "self", ",", "volume_system", ",", "volume_identifiers", ")", ":", "print_header", "=", "True", "while", "True", ":", "if", "print_header", ":", "self", ".", "_PrintVSSStoreIdentifiersOverview", "(", "volume_system", ",", "volum...
Retrieves VSS store identifiers. This method can be used to prompt the user to provide VSS store identifiers. Args: volume_system (VShadowVolumeSystem): volume system. volume_identifiers (list[str]): volume identifiers including prefix. Returns: list[str]: selected volume identifiers including prefix or None.
[ "Retrieves", "VSS", "store", "identifiers", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/command_line.py#L689-L732
train
208,328
log2timeline/dfvfs
dfvfs/helpers/command_line.py
CLIVolumeScannerMediator.UnlockEncryptedVolume
def UnlockEncryptedVolume( self, source_scanner_object, scan_context, locked_scan_node, credentials): """Unlocks an encrypted volume. This method can be used to prompt the user to provide encrypted volume credentials. Args: source_scanner_object (SourceScanner): source scanner. scan_context (SourceScannerContext): source scanner context. locked_scan_node (SourceScanNode): locked scan node. credentials (Credentials): credentials supported by the locked scan node. Returns: bool: True if the volume was unlocked. """ # TODO: print volume description. if locked_scan_node.type_indicator == ( definitions.TYPE_INDICATOR_APFS_CONTAINER): header = 'Found an APFS encrypted volume.' elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE: header = 'Found a BitLocker encrypted volume.' elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_FVDE: header = 'Found a CoreStorage (FVDE) encrypted volume.' else: header = 'Found an encrypted volume.' self._output_writer.Write(header) credentials_list = list(credentials.CREDENTIALS) credentials_list.append('skip') self._output_writer.Write('Supported credentials:\n\n') for index, name in enumerate(credentials_list): available_credential = ' {0:d}. {1:s}\n'.format(index + 1, name) self._output_writer.Write(available_credential) self._output_writer.Write('\nNote that you can abort with Ctrl^C.\n\n') result = False while not result: self._output_writer.Write('Select a credential to unlock the volume: ') input_line = self._input_reader.Read() input_line = input_line.strip() if input_line in credentials_list: credential_type = input_line else: try: credential_type = int(input_line, 10) credential_type = credentials_list[credential_type - 1] except (IndexError, ValueError): self._output_writer.Write( 'Unsupported credential: {0:s}\n'.format(input_line)) continue if credential_type == 'skip': break getpass_string = 'Enter credential data: ' if sys.platform.startswith('win') and sys.version_info[0] < 3: # For Python 2 on Windows getpass (win_getpass) requires an encoded # byte string. For Python 3 we need it to be a Unicode string. getpass_string = self._EncodeString(getpass_string) credential_data = getpass.getpass(getpass_string) self._output_writer.Write('\n') if credential_type == 'key': try: credential_data = credential_data.decode('hex') except TypeError: self._output_writer.Write('Unsupported credential data.\n') continue result = source_scanner_object.Unlock( scan_context, locked_scan_node.path_spec, credential_type, credential_data) if not result: self._output_writer.Write('Unable to unlock volume.\n\n') return result
python
def UnlockEncryptedVolume( self, source_scanner_object, scan_context, locked_scan_node, credentials): """Unlocks an encrypted volume. This method can be used to prompt the user to provide encrypted volume credentials. Args: source_scanner_object (SourceScanner): source scanner. scan_context (SourceScannerContext): source scanner context. locked_scan_node (SourceScanNode): locked scan node. credentials (Credentials): credentials supported by the locked scan node. Returns: bool: True if the volume was unlocked. """ # TODO: print volume description. if locked_scan_node.type_indicator == ( definitions.TYPE_INDICATOR_APFS_CONTAINER): header = 'Found an APFS encrypted volume.' elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_BDE: header = 'Found a BitLocker encrypted volume.' elif locked_scan_node.type_indicator == definitions.TYPE_INDICATOR_FVDE: header = 'Found a CoreStorage (FVDE) encrypted volume.' else: header = 'Found an encrypted volume.' self._output_writer.Write(header) credentials_list = list(credentials.CREDENTIALS) credentials_list.append('skip') self._output_writer.Write('Supported credentials:\n\n') for index, name in enumerate(credentials_list): available_credential = ' {0:d}. {1:s}\n'.format(index + 1, name) self._output_writer.Write(available_credential) self._output_writer.Write('\nNote that you can abort with Ctrl^C.\n\n') result = False while not result: self._output_writer.Write('Select a credential to unlock the volume: ') input_line = self._input_reader.Read() input_line = input_line.strip() if input_line in credentials_list: credential_type = input_line else: try: credential_type = int(input_line, 10) credential_type = credentials_list[credential_type - 1] except (IndexError, ValueError): self._output_writer.Write( 'Unsupported credential: {0:s}\n'.format(input_line)) continue if credential_type == 'skip': break getpass_string = 'Enter credential data: ' if sys.platform.startswith('win') and sys.version_info[0] < 3: # For Python 2 on Windows getpass (win_getpass) requires an encoded # byte string. For Python 3 we need it to be a Unicode string. getpass_string = self._EncodeString(getpass_string) credential_data = getpass.getpass(getpass_string) self._output_writer.Write('\n') if credential_type == 'key': try: credential_data = credential_data.decode('hex') except TypeError: self._output_writer.Write('Unsupported credential data.\n') continue result = source_scanner_object.Unlock( scan_context, locked_scan_node.path_spec, credential_type, credential_data) if not result: self._output_writer.Write('Unable to unlock volume.\n\n') return result
[ "def", "UnlockEncryptedVolume", "(", "self", ",", "source_scanner_object", ",", "scan_context", ",", "locked_scan_node", ",", "credentials", ")", ":", "# TODO: print volume description.", "if", "locked_scan_node", ".", "type_indicator", "==", "(", "definitions", ".", "T...
Unlocks an encrypted volume. This method can be used to prompt the user to provide encrypted volume credentials. Args: source_scanner_object (SourceScanner): source scanner. scan_context (SourceScannerContext): source scanner context. locked_scan_node (SourceScanNode): locked scan node. credentials (Credentials): credentials supported by the locked scan node. Returns: bool: True if the volume was unlocked.
[ "Unlocks", "an", "encrypted", "volume", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/command_line.py#L734-L818
train
208,329
log2timeline/dfvfs
dfvfs/vfs/tar_file_entry.py
TARFileEntry.GetTARInfo
def GetTARInfo(self): """Retrieves the TAR info. Returns: tarfile.TARInfo: TAR info or None if it does not exist. Raises: PathSpecError: if the path specification is incorrect. """ if not self._tar_info: location = getattr(self.path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self._file_system.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) == 1: return None tar_file = self._file_system.GetTARFile() try: self._tar_info = tar_file.getmember(location[1:]) except KeyError: pass return self._tar_info
python
def GetTARInfo(self): """Retrieves the TAR info. Returns: tarfile.TARInfo: TAR info or None if it does not exist. Raises: PathSpecError: if the path specification is incorrect. """ if not self._tar_info: location = getattr(self.path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self._file_system.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) == 1: return None tar_file = self._file_system.GetTARFile() try: self._tar_info = tar_file.getmember(location[1:]) except KeyError: pass return self._tar_info
[ "def", "GetTARInfo", "(", "self", ")", ":", "if", "not", "self", ".", "_tar_info", ":", "location", "=", "getattr", "(", "self", ".", "path_spec", ",", "'location'", ",", "None", ")", "if", "location", "is", "None", ":", "raise", "errors", ".", "PathSp...
Retrieves the TAR info. Returns: tarfile.TARInfo: TAR info or None if it does not exist. Raises: PathSpecError: if the path specification is incorrect.
[ "Retrieves", "the", "TAR", "info", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tar_file_entry.py#L249-L275
train
208,330
log2timeline/dfvfs
dfvfs/encoding/manager.py
EncodingManager.GetDecoder
def GetDecoder(cls, encoding_method): """Retrieves the decoder object for a specific encoding method. Args: encoding_method (str): encoding method identifier. Returns: Decoder: decoder or None if the encoding method does not exists. """ encoding_method = encoding_method.lower() decoder = cls._decoders.get(encoding_method, None) if not decoder: return None return decoder()
python
def GetDecoder(cls, encoding_method): """Retrieves the decoder object for a specific encoding method. Args: encoding_method (str): encoding method identifier. Returns: Decoder: decoder or None if the encoding method does not exists. """ encoding_method = encoding_method.lower() decoder = cls._decoders.get(encoding_method, None) if not decoder: return None return decoder()
[ "def", "GetDecoder", "(", "cls", ",", "encoding_method", ")", ":", "encoding_method", "=", "encoding_method", ".", "lower", "(", ")", "decoder", "=", "cls", ".", "_decoders", ".", "get", "(", "encoding_method", ",", "None", ")", "if", "not", "decoder", ":"...
Retrieves the decoder object for a specific encoding method. Args: encoding_method (str): encoding method identifier. Returns: Decoder: decoder or None if the encoding method does not exists.
[ "Retrieves", "the", "decoder", "object", "for", "a", "specific", "encoding", "method", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/encoding/manager.py#L31-L45
train
208,331
log2timeline/dfvfs
dfvfs/encoding/manager.py
EncodingManager.RegisterDecoder
def RegisterDecoder(cls, decoder): """Registers a decoder for a specific encoding method. Args: decoder (type): decoder class. Raises: KeyError: if the corresponding decoder is already set. """ encoding_method = decoder.ENCODING_METHOD.lower() if encoding_method in cls._decoders: raise KeyError( 'Decoder for encoding method: {0:s} already set.'.format( decoder.ENCODING_METHOD)) cls._decoders[encoding_method] = decoder
python
def RegisterDecoder(cls, decoder): """Registers a decoder for a specific encoding method. Args: decoder (type): decoder class. Raises: KeyError: if the corresponding decoder is already set. """ encoding_method = decoder.ENCODING_METHOD.lower() if encoding_method in cls._decoders: raise KeyError( 'Decoder for encoding method: {0:s} already set.'.format( decoder.ENCODING_METHOD)) cls._decoders[encoding_method] = decoder
[ "def", "RegisterDecoder", "(", "cls", ",", "decoder", ")", ":", "encoding_method", "=", "decoder", ".", "ENCODING_METHOD", ".", "lower", "(", ")", "if", "encoding_method", "in", "cls", ".", "_decoders", ":", "raise", "KeyError", "(", "'Decoder for encoding metho...
Registers a decoder for a specific encoding method. Args: decoder (type): decoder class. Raises: KeyError: if the corresponding decoder is already set.
[ "Registers", "a", "decoder", "for", "a", "specific", "encoding", "method", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/encoding/manager.py#L48-L63
train
208,332
log2timeline/dfvfs
dfvfs/vfs/lvm_file_entry.py
LVMFileEntry._GetDirectory
def _GetDirectory(self): """Retrieves the directory. Returns: LVMDirectory: a directory or None if not available. """ if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return LVMDirectory(self._file_system, self.path_spec)
python
def _GetDirectory(self): """Retrieves the directory. Returns: LVMDirectory: a directory or None if not available. """ if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return LVMDirectory(self._file_system, self.path_spec)
[ "def", "_GetDirectory", "(", "self", ")", ":", "if", "self", ".", "entry_type", "!=", "definitions", ".", "FILE_ENTRY_TYPE_DIRECTORY", ":", "return", "None", "return", "LVMDirectory", "(", "self", ".", "_file_system", ",", "self", ".", "path_spec", ")" ]
Retrieves the directory. Returns: LVMDirectory: a directory or None if not available.
[ "Retrieves", "the", "directory", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/lvm_file_entry.py#L79-L87
train
208,333
log2timeline/dfvfs
dfvfs/lib/tsk_partition.py
GetTSKVsPartByPathSpec
def GetTSKVsPartByPathSpec(tsk_volume, path_spec): """Retrieves the TSK volume system part object from the TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. path_spec (PathSpec): path specification. Returns: tuple: contains: pytsk3.TSK_VS_PART_INFO: TSK volume system part information or None on error. int: partition index or None if not available. """ location = getattr(path_spec, 'location', None) part_index = getattr(path_spec, 'part_index', None) start_offset = getattr(path_spec, 'start_offset', None) partition_index = None if part_index is None: if location is not None: if location.startswith('/p'): try: partition_index = int(location[2:], 10) - 1 except ValueError: pass if partition_index is None or partition_index < 0: location = None if location is None and start_offset is None: return None, None bytes_per_sector = TSKVolumeGetBytesPerSector(tsk_volume) current_part_index = 0 current_partition_index = 0 tsk_vs_part = None # pytsk3 does not handle the Volume_Info iterator correctly therefore # the explicit cast to list is needed to prevent the iterator terminating # too soon or looping forever. tsk_vs_part_list = list(tsk_volume) number_of_tsk_vs_parts = len(tsk_vs_part_list) if number_of_tsk_vs_parts > 0: if (part_index is not None and (part_index < 0 or part_index >= number_of_tsk_vs_parts)): return None, None for tsk_vs_part in tsk_vs_part_list: if TSKVsPartIsAllocated(tsk_vs_part): if partition_index is not None: if partition_index == current_partition_index: break current_partition_index += 1 if part_index is not None and part_index == current_part_index: break if start_offset is not None: start_sector = TSKVsPartGetStartSector(tsk_vs_part) if start_sector is not None: start_sector *= bytes_per_sector if start_sector == start_offset: break current_part_index += 1 # Note that here we cannot solely rely on testing if tsk_vs_part is set # since the for loop will exit with tsk_vs_part set. if tsk_vs_part is None or current_part_index >= number_of_tsk_vs_parts: return None, None if not TSKVsPartIsAllocated(tsk_vs_part): current_partition_index = None return tsk_vs_part, current_partition_index
python
def GetTSKVsPartByPathSpec(tsk_volume, path_spec): """Retrieves the TSK volume system part object from the TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. path_spec (PathSpec): path specification. Returns: tuple: contains: pytsk3.TSK_VS_PART_INFO: TSK volume system part information or None on error. int: partition index or None if not available. """ location = getattr(path_spec, 'location', None) part_index = getattr(path_spec, 'part_index', None) start_offset = getattr(path_spec, 'start_offset', None) partition_index = None if part_index is None: if location is not None: if location.startswith('/p'): try: partition_index = int(location[2:], 10) - 1 except ValueError: pass if partition_index is None or partition_index < 0: location = None if location is None and start_offset is None: return None, None bytes_per_sector = TSKVolumeGetBytesPerSector(tsk_volume) current_part_index = 0 current_partition_index = 0 tsk_vs_part = None # pytsk3 does not handle the Volume_Info iterator correctly therefore # the explicit cast to list is needed to prevent the iterator terminating # too soon or looping forever. tsk_vs_part_list = list(tsk_volume) number_of_tsk_vs_parts = len(tsk_vs_part_list) if number_of_tsk_vs_parts > 0: if (part_index is not None and (part_index < 0 or part_index >= number_of_tsk_vs_parts)): return None, None for tsk_vs_part in tsk_vs_part_list: if TSKVsPartIsAllocated(tsk_vs_part): if partition_index is not None: if partition_index == current_partition_index: break current_partition_index += 1 if part_index is not None and part_index == current_part_index: break if start_offset is not None: start_sector = TSKVsPartGetStartSector(tsk_vs_part) if start_sector is not None: start_sector *= bytes_per_sector if start_sector == start_offset: break current_part_index += 1 # Note that here we cannot solely rely on testing if tsk_vs_part is set # since the for loop will exit with tsk_vs_part set. if tsk_vs_part is None or current_part_index >= number_of_tsk_vs_parts: return None, None if not TSKVsPartIsAllocated(tsk_vs_part): current_partition_index = None return tsk_vs_part, current_partition_index
[ "def", "GetTSKVsPartByPathSpec", "(", "tsk_volume", ",", "path_spec", ")", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "part_index", "=", "getattr", "(", "path_spec", ",", "'part_index'", ",", "None", ")", "start_off...
Retrieves the TSK volume system part object from the TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. path_spec (PathSpec): path specification. Returns: tuple: contains: pytsk3.TSK_VS_PART_INFO: TSK volume system part information or None on error. int: partition index or None if not available.
[ "Retrieves", "the", "TSK", "volume", "system", "part", "object", "from", "the", "TSK", "volume", "object", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/tsk_partition.py#L9-L85
train
208,334
log2timeline/dfvfs
dfvfs/lib/tsk_partition.py
TSKVolumeGetBytesPerSector
def TSKVolumeGetBytesPerSector(tsk_volume): """Retrieves the number of bytes per sector from a TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. Returns: int: number of bytes per sector or 512 by default. """ # Note that because pytsk3.Volume_Info does not explicitly defines info # we need to check if the attribute exists and has a value other # than None. Default to 512 otherwise. if hasattr(tsk_volume, 'info') and tsk_volume.info is not None: block_size = getattr(tsk_volume.info, 'block_size', 512) else: block_size = 512 return block_size
python
def TSKVolumeGetBytesPerSector(tsk_volume): """Retrieves the number of bytes per sector from a TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. Returns: int: number of bytes per sector or 512 by default. """ # Note that because pytsk3.Volume_Info does not explicitly defines info # we need to check if the attribute exists and has a value other # than None. Default to 512 otherwise. if hasattr(tsk_volume, 'info') and tsk_volume.info is not None: block_size = getattr(tsk_volume.info, 'block_size', 512) else: block_size = 512 return block_size
[ "def", "TSKVolumeGetBytesPerSector", "(", "tsk_volume", ")", ":", "# Note that because pytsk3.Volume_Info does not explicitly defines info", "# we need to check if the attribute exists and has a value other", "# than None. Default to 512 otherwise.", "if", "hasattr", "(", "tsk_volume", ","...
Retrieves the number of bytes per sector from a TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. Returns: int: number of bytes per sector or 512 by default.
[ "Retrieves", "the", "number", "of", "bytes", "per", "sector", "from", "a", "TSK", "volume", "object", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/tsk_partition.py#L88-L105
train
208,335
log2timeline/dfvfs
dfvfs/file_io/vhdi_file_io.py
VHDIFile._OpenParentFile
def _OpenParentFile(self, file_system, path_spec, vhdi_file): """Opens the parent file. Args: file_system (FileSystem): file system of the VHDI file. path_spec (PathSpec): path specification of the VHDI file. vhdi_file (pyvhdi.file): VHDI file. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if not location: raise errors.PathSpecError( 'Unsupported path specification without location.') location_path_segments = file_system.SplitPath(location) parent_filename = vhdi_file.parent_filename _, _, parent_filename = parent_filename.rpartition('\\') location_path_segments.pop() location_path_segments.append(parent_filename) parent_file_location = file_system.JoinPath(location_path_segments) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(path_spec) kwargs['location'] = parent_file_location if path_spec.parent is not None: kwargs['parent'] = path_spec.parent parent_file_path_spec = path_spec_factory.Factory.NewPathSpec( path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(parent_file_path_spec): return file_object = resolver.Resolver.OpenFileObject( parent_file_path_spec, resolver_context=self._resolver_context) vhdi_parent_file = pyvhdi.file() vhdi_parent_file.open_file_object(file_object) if vhdi_parent_file.parent_identifier: self._OpenParentFile( file_system, parent_file_path_spec, vhdi_parent_file) vhdi_file.set_parent(vhdi_parent_file) self._parent_vhdi_files.append(vhdi_parent_file) self._sub_file_objects.append(file_object)
python
def _OpenParentFile(self, file_system, path_spec, vhdi_file): """Opens the parent file. Args: file_system (FileSystem): file system of the VHDI file. path_spec (PathSpec): path specification of the VHDI file. vhdi_file (pyvhdi.file): VHDI file. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if not location: raise errors.PathSpecError( 'Unsupported path specification without location.') location_path_segments = file_system.SplitPath(location) parent_filename = vhdi_file.parent_filename _, _, parent_filename = parent_filename.rpartition('\\') location_path_segments.pop() location_path_segments.append(parent_filename) parent_file_location = file_system.JoinPath(location_path_segments) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(path_spec) kwargs['location'] = parent_file_location if path_spec.parent is not None: kwargs['parent'] = path_spec.parent parent_file_path_spec = path_spec_factory.Factory.NewPathSpec( path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(parent_file_path_spec): return file_object = resolver.Resolver.OpenFileObject( parent_file_path_spec, resolver_context=self._resolver_context) vhdi_parent_file = pyvhdi.file() vhdi_parent_file.open_file_object(file_object) if vhdi_parent_file.parent_identifier: self._OpenParentFile( file_system, parent_file_path_spec, vhdi_parent_file) vhdi_file.set_parent(vhdi_parent_file) self._parent_vhdi_files.append(vhdi_parent_file) self._sub_file_objects.append(file_object)
[ "def", "_OpenParentFile", "(", "self", ",", "file_system", ",", "path_spec", ",", "vhdi_file", ")", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "if", "not", "location", ":", "raise", "errors", ".", "PathSpecError",...
Opens the parent file. Args: file_system (FileSystem): file system of the VHDI file. path_spec (PathSpec): path specification of the VHDI file. vhdi_file (pyvhdi.file): VHDI file. Raises: PathSpecError: if the path specification is incorrect.
[ "Opens", "the", "parent", "file", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/vhdi_file_io.py#L79-L132
train
208,336
log2timeline/dfvfs
dfvfs/encryption/manager.py
EncryptionManager.DeregisterDecrypter
def DeregisterDecrypter(cls, decrypter): """Deregisters a decrypter for a specific encryption method. Args: decrypter (type): decrypter class. Raises: KeyError: if the corresponding decrypter is not set. """ encryption_method = decrypter.ENCRYPTION_METHOD.lower() if encryption_method not in cls._decrypters: raise KeyError( 'Decrypter for encryption method: {0:s} not set.'.format( decrypter.ENCRYPTION_METHOD)) del cls._decrypters[encryption_method]
python
def DeregisterDecrypter(cls, decrypter): """Deregisters a decrypter for a specific encryption method. Args: decrypter (type): decrypter class. Raises: KeyError: if the corresponding decrypter is not set. """ encryption_method = decrypter.ENCRYPTION_METHOD.lower() if encryption_method not in cls._decrypters: raise KeyError( 'Decrypter for encryption method: {0:s} not set.'.format( decrypter.ENCRYPTION_METHOD)) del cls._decrypters[encryption_method]
[ "def", "DeregisterDecrypter", "(", "cls", ",", "decrypter", ")", ":", "encryption_method", "=", "decrypter", ".", "ENCRYPTION_METHOD", ".", "lower", "(", ")", "if", "encryption_method", "not", "in", "cls", ".", "_decrypters", ":", "raise", "KeyError", "(", "'D...
Deregisters a decrypter for a specific encryption method. Args: decrypter (type): decrypter class. Raises: KeyError: if the corresponding decrypter is not set.
[ "Deregisters", "a", "decrypter", "for", "a", "specific", "encryption", "method", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/encryption/manager.py#L13-L28
train
208,337
log2timeline/dfvfs
dfvfs/encryption/manager.py
EncryptionManager.GetDecrypter
def GetDecrypter(cls, encryption_method, **kwargs): """Retrieves the decrypter object for a specific encryption method. Args: encryption_method (str): encryption method identifier. kwargs (dict): keyword arguments depending on the decrypter. Returns: Decrypter: decrypter or None if the encryption method does not exists. Raises: CredentialError: if the necessary credentials are missing. """ encryption_method = encryption_method.lower() decrypter = cls._decrypters.get(encryption_method, None) if not decrypter: return None return decrypter(**kwargs)
python
def GetDecrypter(cls, encryption_method, **kwargs): """Retrieves the decrypter object for a specific encryption method. Args: encryption_method (str): encryption method identifier. kwargs (dict): keyword arguments depending on the decrypter. Returns: Decrypter: decrypter or None if the encryption method does not exists. Raises: CredentialError: if the necessary credentials are missing. """ encryption_method = encryption_method.lower() decrypter = cls._decrypters.get(encryption_method, None) if not decrypter: return None return decrypter(**kwargs)
[ "def", "GetDecrypter", "(", "cls", ",", "encryption_method", ",", "*", "*", "kwargs", ")", ":", "encryption_method", "=", "encryption_method", ".", "lower", "(", ")", "decrypter", "=", "cls", ".", "_decrypters", ".", "get", "(", "encryption_method", ",", "No...
Retrieves the decrypter object for a specific encryption method. Args: encryption_method (str): encryption method identifier. kwargs (dict): keyword arguments depending on the decrypter. Returns: Decrypter: decrypter or None if the encryption method does not exists. Raises: CredentialError: if the necessary credentials are missing.
[ "Retrieves", "the", "decrypter", "object", "for", "a", "specific", "encryption", "method", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/encryption/manager.py#L31-L49
train
208,338
log2timeline/dfvfs
dfvfs/vfs/tar_file_system.py
TARFileSystem.GetTARInfoByPathSpec
def GetTARInfoByPathSpec(self, path_spec): """Retrieves the TAR info for a path specification. Args: path_spec (PathSpec): a path specification. Returns: tarfile.TARInfo: TAR info or None if it does not exist. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) == 1: return None try: return self._tar_file.getmember(location[1:]) except KeyError: pass
python
def GetTARInfoByPathSpec(self, path_spec): """Retrieves the TAR info for a path specification. Args: path_spec (PathSpec): a path specification. Returns: tarfile.TARInfo: TAR info or None if it does not exist. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) == 1: return None try: return self._tar_file.getmember(location[1:]) except KeyError: pass
[ "def", "GetTARInfoByPathSpec", "(", "self", ",", "path_spec", ")", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "if", "location", "is", "None", ":", "raise", "errors", ".", "PathSpecError", "(", "'Path specification m...
Retrieves the TAR info for a path specification. Args: path_spec (PathSpec): a path specification. Returns: tarfile.TARInfo: TAR info or None if it does not exist. Raises: PathSpecError: if the path specification is incorrect.
[ "Retrieves", "the", "TAR", "info", "for", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tar_file_system.py#L165-L190
train
208,339
log2timeline/dfvfs
dfvfs/vfs/cpio_file_system.py
CPIOFileSystem.GetCPIOArchiveFileEntryByPathSpec
def GetCPIOArchiveFileEntryByPathSpec(self, path_spec): """Retrieves the CPIO archive file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: CPIOArchiveFileEntry: CPIO archive file entry or None if not available. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) == 1: return None return self._cpio_archive_file.GetFileEntryByPath(location[1:])
python
def GetCPIOArchiveFileEntryByPathSpec(self, path_spec): """Retrieves the CPIO archive file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: CPIOArchiveFileEntry: CPIO archive file entry or None if not available. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) == 1: return None return self._cpio_archive_file.GetFileEntryByPath(location[1:])
[ "def", "GetCPIOArchiveFileEntryByPathSpec", "(", "self", ",", "path_spec", ")", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "if", "location", "is", "None", ":", "raise", "errors", ".", "PathSpecError", "(", "'Path sp...
Retrieves the CPIO archive file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: CPIOArchiveFileEntry: CPIO archive file entry or None if not available. Raises: PathSpecError: if the path specification is incorrect.
[ "Retrieves", "the", "CPIO", "archive", "file", "entry", "for", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/cpio_file_system.py#L102-L124
train
208,340
log2timeline/dfvfs
dfvfs/helpers/windows_path_resolver.py
WindowsPathResolver._PathStripPrefix
def _PathStripPrefix(self, path): """Strips the prefix from a path. Args: path (str): Windows path to strip the prefix from. Returns: str: path without the prefix or None if the path is not supported. """ if path.startswith('\\\\.\\') or path.startswith('\\\\?\\'): if len(path) < 7 or path[5] != ':' or path[6] != self._PATH_SEPARATOR: # Cannot handle a non-volume path. return None path = path[7:] elif path.startswith('\\\\'): # Cannot handle an UNC path. return None elif len(path) >= 3 and path[1] == ':': # Check if the path is a Volume 'absolute' path. if path[2] != self._PATH_SEPARATOR: # Cannot handle a Volume 'relative' path. return None path = path[3:] elif path.startswith('\\'): path = path[1:] else: # Cannot handle a relative path. return None return path
python
def _PathStripPrefix(self, path): """Strips the prefix from a path. Args: path (str): Windows path to strip the prefix from. Returns: str: path without the prefix or None if the path is not supported. """ if path.startswith('\\\\.\\') or path.startswith('\\\\?\\'): if len(path) < 7 or path[5] != ':' or path[6] != self._PATH_SEPARATOR: # Cannot handle a non-volume path. return None path = path[7:] elif path.startswith('\\\\'): # Cannot handle an UNC path. return None elif len(path) >= 3 and path[1] == ':': # Check if the path is a Volume 'absolute' path. if path[2] != self._PATH_SEPARATOR: # Cannot handle a Volume 'relative' path. return None path = path[3:] elif path.startswith('\\'): path = path[1:] else: # Cannot handle a relative path. return None return path
[ "def", "_PathStripPrefix", "(", "self", ",", "path", ")", ":", "if", "path", ".", "startswith", "(", "'\\\\\\\\.\\\\'", ")", "or", "path", ".", "startswith", "(", "'\\\\\\\\?\\\\'", ")", ":", "if", "len", "(", "path", ")", "<", "7", "or", "path", "[", ...
Strips the prefix from a path. Args: path (str): Windows path to strip the prefix from. Returns: str: path without the prefix or None if the path is not supported.
[ "Strips", "the", "prefix", "from", "a", "path", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/windows_path_resolver.py#L70-L105
train
208,341
log2timeline/dfvfs
dfvfs/helpers/windows_path_resolver.py
WindowsPathResolver.SetEnvironmentVariable
def SetEnvironmentVariable(self, name, value): """Sets an environment variable in the Windows path helper. Args: name (str): name of the environment variable without enclosing %-characters, e.g. SystemRoot as in %SystemRoot%. value (str): value of the environment variable. """ if isinstance(value, py2to3.STRING_TYPES): value = self._PathStripPrefix(value) if value is not None: self._environment_variables[name.upper()] = value
python
def SetEnvironmentVariable(self, name, value): """Sets an environment variable in the Windows path helper. Args: name (str): name of the environment variable without enclosing %-characters, e.g. SystemRoot as in %SystemRoot%. value (str): value of the environment variable. """ if isinstance(value, py2to3.STRING_TYPES): value = self._PathStripPrefix(value) if value is not None: self._environment_variables[name.upper()] = value
[ "def", "SetEnvironmentVariable", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "py2to3", ".", "STRING_TYPES", ")", ":", "value", "=", "self", ".", "_PathStripPrefix", "(", "value", ")", "if", "value", "is", "not...
Sets an environment variable in the Windows path helper. Args: name (str): name of the environment variable without enclosing %-characters, e.g. SystemRoot as in %SystemRoot%. value (str): value of the environment variable.
[ "Sets", "an", "environment", "variable", "in", "the", "Windows", "path", "helper", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/windows_path_resolver.py#L261-L273
train
208,342
log2timeline/dfvfs
dfvfs/lib/apfs_helper.py
APFSUnlockVolume
def APFSUnlockVolume(fsapfs_volume, path_spec, key_chain): """Unlocks an APFS volume using the path specification. Args: fsapfs_volume (pyapfs.volume): APFS volume. path_spec (PathSpec): path specification. key_chain (KeyChain): key chain. Returns: bool: True if the volume is unlocked, False otherwise. """ is_locked = fsapfs_volume.is_locked() if is_locked: password = key_chain.GetCredential(path_spec, 'password') if password: fsapfs_volume.set_password(password) recovery_password = key_chain.GetCredential(path_spec, 'recovery_password') if recovery_password: fsapfs_volume.set_recovery_password(recovery_password) is_locked = not fsapfs_volume.unlock() return not is_locked
python
def APFSUnlockVolume(fsapfs_volume, path_spec, key_chain): """Unlocks an APFS volume using the path specification. Args: fsapfs_volume (pyapfs.volume): APFS volume. path_spec (PathSpec): path specification. key_chain (KeyChain): key chain. Returns: bool: True if the volume is unlocked, False otherwise. """ is_locked = fsapfs_volume.is_locked() if is_locked: password = key_chain.GetCredential(path_spec, 'password') if password: fsapfs_volume.set_password(password) recovery_password = key_chain.GetCredential(path_spec, 'recovery_password') if recovery_password: fsapfs_volume.set_recovery_password(recovery_password) is_locked = not fsapfs_volume.unlock() return not is_locked
[ "def", "APFSUnlockVolume", "(", "fsapfs_volume", ",", "path_spec", ",", "key_chain", ")", ":", "is_locked", "=", "fsapfs_volume", ".", "is_locked", "(", ")", "if", "is_locked", ":", "password", "=", "key_chain", ".", "GetCredential", "(", "path_spec", ",", "'p...
Unlocks an APFS volume using the path specification. Args: fsapfs_volume (pyapfs.volume): APFS volume. path_spec (PathSpec): path specification. key_chain (KeyChain): key chain. Returns: bool: True if the volume is unlocked, False otherwise.
[ "Unlocks", "an", "APFS", "volume", "using", "the", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/apfs_helper.py#L35-L58
train
208,343
log2timeline/dfvfs
dfvfs/file_io/sqlite_blob_file_io.py
SQLiteBlobFile.GetNumberOfRows
def GetNumberOfRows(self): """Retrieves the number of rows of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened. """ if not self._database_object: raise IOError('Not opened.') if self._number_of_rows is None: self._number_of_rows = self._database_object.GetNumberOfRows( self._table_name) return self._number_of_rows
python
def GetNumberOfRows(self): """Retrieves the number of rows of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened. """ if not self._database_object: raise IOError('Not opened.') if self._number_of_rows is None: self._number_of_rows = self._database_object.GetNumberOfRows( self._table_name) return self._number_of_rows
[ "def", "GetNumberOfRows", "(", "self", ")", ":", "if", "not", "self", ".", "_database_object", ":", "raise", "IOError", "(", "'Not opened.'", ")", "if", "self", ".", "_number_of_rows", "is", "None", ":", "self", ".", "_number_of_rows", "=", "self", ".", "_...
Retrieves the number of rows of the table. Returns: int: number of rows. Raises: IOError: if the file-like object has not been opened. OSError: if the file-like object has not been opened.
[ "Retrieves", "the", "number", "of", "rows", "of", "the", "table", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/sqlite_blob_file_io.py#L159-L176
train
208,344
log2timeline/dfvfs
dfvfs/vfs/zip_file_system.py
ZipFileSystem.GetZipInfoByPathSpec
def GetZipInfoByPathSpec(self, path_spec): """Retrieves the ZIP info for a path specification. Args: path_spec (PathSpec): a path specification. Returns: zipfile.ZipInfo: a ZIP info object or None if not available. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) > 1: return self._zip_file.getinfo(location[1:]) return None
python
def GetZipInfoByPathSpec(self, path_spec): """Retrieves the ZIP info for a path specification. Args: path_spec (PathSpec): a path specification. Returns: zipfile.ZipInfo: a ZIP info object or None if not available. Raises: PathSpecError: if the path specification is incorrect. """ location = getattr(path_spec, 'location', None) if location is None: raise errors.PathSpecError('Path specification missing location.') if not location.startswith(self.LOCATION_ROOT): raise errors.PathSpecError('Invalid location in path specification.') if len(location) > 1: return self._zip_file.getinfo(location[1:]) return None
[ "def", "GetZipInfoByPathSpec", "(", "self", ",", "path_spec", ")", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "if", "location", "is", "None", ":", "raise", "errors", ".", "PathSpecError", "(", "'Path specification m...
Retrieves the ZIP info for a path specification. Args: path_spec (PathSpec): a path specification. Returns: zipfile.ZipInfo: a ZIP info object or None if not available. Raises: PathSpecError: if the path specification is incorrect.
[ "Retrieves", "the", "ZIP", "info", "for", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/zip_file_system.py#L159-L181
train
208,345
log2timeline/dfvfs
dfvfs/vfs/apfs_file_system.py
APFSFileSystem.GetAPFSFileEntryByPathSpec
def GetAPFSFileEntryByPathSpec(self, path_spec): """Retrieves the APFS file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: pyfsapfs.file_entry: file entry. Raises: PathSpecError: if the path specification is missing location and identifier. """ # Opening a file by identifier is faster than opening a file by location. location = getattr(path_spec, 'location', None) identifier = getattr(path_spec, 'identifier', None) if identifier is not None: fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_identifier( identifier) elif location is not None: fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_path(location) else: raise errors.PathSpecError( 'Path specification missing location and identifier.') return fsapfs_file_entry
python
def GetAPFSFileEntryByPathSpec(self, path_spec): """Retrieves the APFS file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: pyfsapfs.file_entry: file entry. Raises: PathSpecError: if the path specification is missing location and identifier. """ # Opening a file by identifier is faster than opening a file by location. location = getattr(path_spec, 'location', None) identifier = getattr(path_spec, 'identifier', None) if identifier is not None: fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_identifier( identifier) elif location is not None: fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_path(location) else: raise errors.PathSpecError( 'Path specification missing location and identifier.') return fsapfs_file_entry
[ "def", "GetAPFSFileEntryByPathSpec", "(", "self", ",", "path_spec", ")", ":", "# Opening a file by identifier is faster than opening a file by location.", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ",", "None", ")", "identifier", "=", "getattr", "(",...
Retrieves the APFS file entry for a path specification. Args: path_spec (PathSpec): a path specification. Returns: pyfsapfs.file_entry: file entry. Raises: PathSpecError: if the path specification is missing location and identifier.
[ "Retrieves", "the", "APFS", "file", "entry", "for", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/apfs_file_system.py#L152-L178
train
208,346
log2timeline/dfvfs
dfvfs/path/factory.py
Factory.DeregisterPathSpec
def DeregisterPathSpec(cls, path_spec_type): """Deregisters a path specification. Args: path_spec_type (type): path specification type. Raises: KeyError: if path specification is not registered. """ type_indicator = path_spec_type.TYPE_INDICATOR if type_indicator not in cls._path_spec_types: raise KeyError( 'Path specification type: {0:s} not set.'.format(type_indicator)) del cls._path_spec_types[type_indicator] if type_indicator in cls._system_level_type_indicators: del cls._system_level_type_indicators[type_indicator]
python
def DeregisterPathSpec(cls, path_spec_type): """Deregisters a path specification. Args: path_spec_type (type): path specification type. Raises: KeyError: if path specification is not registered. """ type_indicator = path_spec_type.TYPE_INDICATOR if type_indicator not in cls._path_spec_types: raise KeyError( 'Path specification type: {0:s} not set.'.format(type_indicator)) del cls._path_spec_types[type_indicator] if type_indicator in cls._system_level_type_indicators: del cls._system_level_type_indicators[type_indicator]
[ "def", "DeregisterPathSpec", "(", "cls", ",", "path_spec_type", ")", ":", "type_indicator", "=", "path_spec_type", ".", "TYPE_INDICATOR", "if", "type_indicator", "not", "in", "cls", ".", "_path_spec_types", ":", "raise", "KeyError", "(", "'Path specification type: {0:...
Deregisters a path specification. Args: path_spec_type (type): path specification type. Raises: KeyError: if path specification is not registered.
[ "Deregisters", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/path/factory.py#L42-L59
train
208,347
log2timeline/dfvfs
dfvfs/path/factory.py
Factory.GetProperties
def GetProperties(cls, path_spec): """Retrieves a dictionary containing the path specification properties. Args: path_spec (PathSpec): path specification. Returns: dict[str, str]: path specification properties. Raises: dict: path specification properties. """ properties = {} for property_name in cls.PROPERTY_NAMES: # Note that we do not want to set the properties when not used. if hasattr(path_spec, property_name): properties[property_name] = getattr(path_spec, property_name) return properties
python
def GetProperties(cls, path_spec): """Retrieves a dictionary containing the path specification properties. Args: path_spec (PathSpec): path specification. Returns: dict[str, str]: path specification properties. Raises: dict: path specification properties. """ properties = {} for property_name in cls.PROPERTY_NAMES: # Note that we do not want to set the properties when not used. if hasattr(path_spec, property_name): properties[property_name] = getattr(path_spec, property_name) return properties
[ "def", "GetProperties", "(", "cls", ",", "path_spec", ")", ":", "properties", "=", "{", "}", "for", "property_name", "in", "cls", ".", "PROPERTY_NAMES", ":", "# Note that we do not want to set the properties when not used.", "if", "hasattr", "(", "path_spec", ",", "...
Retrieves a dictionary containing the path specification properties. Args: path_spec (PathSpec): path specification. Returns: dict[str, str]: path specification properties. Raises: dict: path specification properties.
[ "Retrieves", "a", "dictionary", "containing", "the", "path", "specification", "properties", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/path/factory.py#L62-L81
train
208,348
log2timeline/dfvfs
dfvfs/path/factory.py
Factory.NewPathSpec
def NewPathSpec(cls, type_indicator, **kwargs): """Creates a new path specification for the specific type indicator. Args: type_indicator (str): type indicator. kwargs (dict): keyword arguments depending on the path specification. Returns: PathSpec: path specification. Raises: KeyError: if path specification is not registered. """ if type_indicator not in cls._path_spec_types: raise KeyError( 'Path specification type: {0:s} not set.'.format(type_indicator)) # An empty parent will cause parentless path specifications to raise # so we conveniently remove it here. if 'parent' in kwargs and kwargs['parent'] is None: del kwargs['parent'] path_spec_type = cls._path_spec_types[type_indicator] return path_spec_type(**kwargs)
python
def NewPathSpec(cls, type_indicator, **kwargs): """Creates a new path specification for the specific type indicator. Args: type_indicator (str): type indicator. kwargs (dict): keyword arguments depending on the path specification. Returns: PathSpec: path specification. Raises: KeyError: if path specification is not registered. """ if type_indicator not in cls._path_spec_types: raise KeyError( 'Path specification type: {0:s} not set.'.format(type_indicator)) # An empty parent will cause parentless path specifications to raise # so we conveniently remove it here. if 'parent' in kwargs and kwargs['parent'] is None: del kwargs['parent'] path_spec_type = cls._path_spec_types[type_indicator] return path_spec_type(**kwargs)
[ "def", "NewPathSpec", "(", "cls", ",", "type_indicator", ",", "*", "*", "kwargs", ")", ":", "if", "type_indicator", "not", "in", "cls", ".", "_path_spec_types", ":", "raise", "KeyError", "(", "'Path specification type: {0:s} not set.'", ".", "format", "(", "type...
Creates a new path specification for the specific type indicator. Args: type_indicator (str): type indicator. kwargs (dict): keyword arguments depending on the path specification. Returns: PathSpec: path specification. Raises: KeyError: if path specification is not registered.
[ "Creates", "a", "new", "path", "specification", "for", "the", "specific", "type", "indicator", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/path/factory.py#L96-L119
train
208,349
log2timeline/dfvfs
dfvfs/path/factory.py
Factory.RegisterPathSpec
def RegisterPathSpec(cls, path_spec_type): """Registers a path specification type. Args: path_spec_type (type): path specification type. Raises: KeyError: if path specification is already registered. """ type_indicator = path_spec_type.TYPE_INDICATOR if type_indicator in cls._path_spec_types: raise KeyError( 'Path specification type: {0:s} already set.'.format( type_indicator)) cls._path_spec_types[type_indicator] = path_spec_type if getattr(path_spec_type, '_IS_SYSTEM_LEVEL', False): cls._system_level_type_indicators[type_indicator] = path_spec_type
python
def RegisterPathSpec(cls, path_spec_type): """Registers a path specification type. Args: path_spec_type (type): path specification type. Raises: KeyError: if path specification is already registered. """ type_indicator = path_spec_type.TYPE_INDICATOR if type_indicator in cls._path_spec_types: raise KeyError( 'Path specification type: {0:s} already set.'.format( type_indicator)) cls._path_spec_types[type_indicator] = path_spec_type if getattr(path_spec_type, '_IS_SYSTEM_LEVEL', False): cls._system_level_type_indicators[type_indicator] = path_spec_type
[ "def", "RegisterPathSpec", "(", "cls", ",", "path_spec_type", ")", ":", "type_indicator", "=", "path_spec_type", ".", "TYPE_INDICATOR", "if", "type_indicator", "in", "cls", ".", "_path_spec_types", ":", "raise", "KeyError", "(", "'Path specification type: {0:s} already ...
Registers a path specification type. Args: path_spec_type (type): path specification type. Raises: KeyError: if path specification is already registered.
[ "Registers", "a", "path", "specification", "type", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/path/factory.py#L122-L140
train
208,350
log2timeline/dfvfs
dfvfs/lib/data_format.py
DataFormat._ReadString
def _ReadString( self, file_object, file_offset, data_type_map, description): """Reads a string. Args: file_object (FileIO): file-like object. file_offset (int): offset of the data relative from the start of the file-like object. data_type_map (dtfabric.DataTypeMap): data type map of the string. description (str): description of the string. Returns: object: structure values object. Raises: FileFormatError: if the string cannot be read. ValueError: if file-like object or date type map are invalid. """ # pylint: disable=protected-access element_data_size = ( data_type_map._element_data_type_definition.GetByteSize()) elements_terminator = ( data_type_map._data_type_definition.elements_terminator) byte_stream = [] element_data = file_object.read(element_data_size) byte_stream.append(element_data) while element_data and element_data != elements_terminator: element_data = file_object.read(element_data_size) byte_stream.append(element_data) byte_stream = b''.join(byte_stream) return self._ReadStructureFromByteStream( byte_stream, file_offset, data_type_map, description)
python
def _ReadString( self, file_object, file_offset, data_type_map, description): """Reads a string. Args: file_object (FileIO): file-like object. file_offset (int): offset of the data relative from the start of the file-like object. data_type_map (dtfabric.DataTypeMap): data type map of the string. description (str): description of the string. Returns: object: structure values object. Raises: FileFormatError: if the string cannot be read. ValueError: if file-like object or date type map are invalid. """ # pylint: disable=protected-access element_data_size = ( data_type_map._element_data_type_definition.GetByteSize()) elements_terminator = ( data_type_map._data_type_definition.elements_terminator) byte_stream = [] element_data = file_object.read(element_data_size) byte_stream.append(element_data) while element_data and element_data != elements_terminator: element_data = file_object.read(element_data_size) byte_stream.append(element_data) byte_stream = b''.join(byte_stream) return self._ReadStructureFromByteStream( byte_stream, file_offset, data_type_map, description)
[ "def", "_ReadString", "(", "self", ",", "file_object", ",", "file_offset", ",", "data_type_map", ",", "description", ")", ":", "# pylint: disable=protected-access", "element_data_size", "=", "(", "data_type_map", ".", "_element_data_type_definition", ".", "GetByteSize", ...
Reads a string. Args: file_object (FileIO): file-like object. file_offset (int): offset of the data relative from the start of the file-like object. data_type_map (dtfabric.DataTypeMap): data type map of the string. description (str): description of the string. Returns: object: structure values object. Raises: FileFormatError: if the string cannot be read. ValueError: if file-like object or date type map are invalid.
[ "Reads", "a", "string", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/data_format.py#L56-L91
train
208,351
log2timeline/dfvfs
dfvfs/lib/data_format.py
DataFormat._ReadStructure
def _ReadStructure( self, file_object, file_offset, data_size, data_type_map, description): """Reads a structure. Args: file_object (FileIO): file-like object. file_offset (int): offset of the data relative from the start of the file-like object. data_size (int): data size of the structure. data_type_map (dtfabric.DataTypeMap): data type map of the structure. description (str): description of the structure. Returns: object: structure values object. Raises: FileFormatError: if the structure cannot be read. ValueError: if file-like object or date type map are invalid. """ data = self._ReadData(file_object, file_offset, data_size, description) return self._ReadStructureFromByteStream( data, file_offset, data_type_map, description)
python
def _ReadStructure( self, file_object, file_offset, data_size, data_type_map, description): """Reads a structure. Args: file_object (FileIO): file-like object. file_offset (int): offset of the data relative from the start of the file-like object. data_size (int): data size of the structure. data_type_map (dtfabric.DataTypeMap): data type map of the structure. description (str): description of the structure. Returns: object: structure values object. Raises: FileFormatError: if the structure cannot be read. ValueError: if file-like object or date type map are invalid. """ data = self._ReadData(file_object, file_offset, data_size, description) return self._ReadStructureFromByteStream( data, file_offset, data_type_map, description)
[ "def", "_ReadStructure", "(", "self", ",", "file_object", ",", "file_offset", ",", "data_size", ",", "data_type_map", ",", "description", ")", ":", "data", "=", "self", ".", "_ReadData", "(", "file_object", ",", "file_offset", ",", "data_size", ",", "descripti...
Reads a structure. Args: file_object (FileIO): file-like object. file_offset (int): offset of the data relative from the start of the file-like object. data_size (int): data size of the structure. data_type_map (dtfabric.DataTypeMap): data type map of the structure. description (str): description of the structure. Returns: object: structure values object. Raises: FileFormatError: if the structure cannot be read. ValueError: if file-like object or date type map are invalid.
[ "Reads", "a", "structure", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/data_format.py#L93-L115
train
208,352
log2timeline/dfvfs
dfvfs/lib/tsk_image.py
TSKFileSystemImage.read
def read(self, offset, size): """Reads a byte string from the image object at the specified offset. Args: offset (int): offset where to start reading. size (int): number of bytes to read. Returns: bytes: data read. """ self._file_object.seek(offset, os.SEEK_SET) return self._file_object.read(size)
python
def read(self, offset, size): """Reads a byte string from the image object at the specified offset. Args: offset (int): offset where to start reading. size (int): number of bytes to read. Returns: bytes: data read. """ self._file_object.seek(offset, os.SEEK_SET) return self._file_object.read(size)
[ "def", "read", "(", "self", ",", "offset", ",", "size", ")", ":", "self", ".", "_file_object", ".", "seek", "(", "offset", ",", "os", ".", "SEEK_SET", ")", "return", "self", ".", "_file_object", ".", "read", "(", "size", ")" ]
Reads a byte string from the image object at the specified offset. Args: offset (int): offset where to start reading. size (int): number of bytes to read. Returns: bytes: data read.
[ "Reads", "a", "byte", "string", "from", "the", "image", "object", "at", "the", "specified", "offset", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/tsk_image.py#L44-L55
train
208,353
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
TSKTime.CopyFromDateTimeString
def CopyFromDateTimeString(self, time_string): """Copies a SleuthKit timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) self._timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self.fraction_of_second = microseconds if pytsk3.TSK_VERSION_NUM >= 0x040200ff: self.fraction_of_second *= 1000 else: self.fraction_of_second *= 10 self._normalized_timestamp = None self.is_local_time = False
python
def CopyFromDateTimeString(self, time_string): """Copies a SleuthKit timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC. """ date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds = date_time_values.get('seconds', 0) microseconds = date_time_values.get('microseconds', 0) self._timestamp = self._GetNumberOfSecondsFromElements( year, month, day_of_month, hours, minutes, seconds) self.fraction_of_second = microseconds if pytsk3.TSK_VERSION_NUM >= 0x040200ff: self.fraction_of_second *= 1000 else: self.fraction_of_second *= 10 self._normalized_timestamp = None self.is_local_time = False
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date...
Copies a SleuthKit timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds fraction and time zone offset are optional. The default time zone is UTC.
[ "Copies", "a", "SleuthKit", "timestamp", "from", "a", "date", "and", "time", "string", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L85-L117
train
208,354
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
TSKTime.CopyToDateTimeString
def CopyToDateTimeString(self): """Copies the date time value to a date and time string. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss or YYYY-MM-DD hh:mm:ss.####### or YYYY-MM-DD hh:mm:ss.######### """ if self._timestamp is None: return None number_of_days, hours, minutes, seconds = self._GetTimeValues( self._timestamp) year, month, day_of_month = self._GetDateValues(number_of_days, 1970, 1, 1) if self.fraction_of_second is None: return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( year, month, day_of_month, hours, minutes, seconds) if pytsk3.TSK_VERSION_NUM >= 0x040200ff: return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:09d}'.format( year, month, day_of_month, hours, minutes, seconds, self.fraction_of_second) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}'.format( year, month, day_of_month, hours, minutes, seconds, self.fraction_of_second)
python
def CopyToDateTimeString(self): """Copies the date time value to a date and time string. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss or YYYY-MM-DD hh:mm:ss.####### or YYYY-MM-DD hh:mm:ss.######### """ if self._timestamp is None: return None number_of_days, hours, minutes, seconds = self._GetTimeValues( self._timestamp) year, month, day_of_month = self._GetDateValues(number_of_days, 1970, 1, 1) if self.fraction_of_second is None: return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format( year, month, day_of_month, hours, minutes, seconds) if pytsk3.TSK_VERSION_NUM >= 0x040200ff: return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:09d}'.format( year, month, day_of_month, hours, minutes, seconds, self.fraction_of_second) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}'.format( year, month, day_of_month, hours, minutes, seconds, self.fraction_of_second)
[ "def", "CopyToDateTimeString", "(", "self", ")", ":", "if", "self", ".", "_timestamp", "is", "None", ":", "return", "None", "number_of_days", ",", "hours", ",", "minutes", ",", "seconds", "=", "self", ".", "_GetTimeValues", "(", "self", ".", "_timestamp", ...
Copies the date time value to a date and time string. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss or YYYY-MM-DD hh:mm:ss.####### or YYYY-MM-DD hh:mm:ss.#########
[ "Copies", "the", "date", "time", "value", "to", "a", "date", "and", "time", "string", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L119-L147
train
208,355
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
TSKTime.CopyToStatTimeTuple
def CopyToStatTimeTuple(self): """Copies the SleuthKit timestamp to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error. """ if self.fraction_of_second is None: return self._timestamp, None return super(TSKTime, self).CopyToStatTimeTuple()
python
def CopyToStatTimeTuple(self): """Copies the SleuthKit timestamp to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error. """ if self.fraction_of_second is None: return self._timestamp, None return super(TSKTime, self).CopyToStatTimeTuple()
[ "def", "CopyToStatTimeTuple", "(", "self", ")", ":", "if", "self", ".", "fraction_of_second", "is", "None", ":", "return", "self", ".", "_timestamp", ",", "None", "return", "super", "(", "TSKTime", ",", "self", ")", ".", "CopyToStatTimeTuple", "(", ")" ]
Copies the SleuthKit timestamp to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error.
[ "Copies", "the", "SleuthKit", "timestamp", "to", "a", "stat", "timestamp", "tuple", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L149-L159
train
208,356
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
TSKDataStream.IsDefault
def IsDefault(self): """Determines if the data stream is the default data stream. Returns: bool: True if the data stream is the default data stream, false if not. """ if not self._tsk_attribute or not self._file_system: return True if self._file_system.IsHFS(): attribute_type = getattr(self._tsk_attribute.info, 'type', None) return attribute_type in ( pytsk3.TSK_FS_ATTR_TYPE_HFS_DEFAULT, pytsk3.TSK_FS_ATTR_TYPE_HFS_DATA) if self._file_system.IsNTFS(): return not bool(self.name) return True
python
def IsDefault(self): """Determines if the data stream is the default data stream. Returns: bool: True if the data stream is the default data stream, false if not. """ if not self._tsk_attribute or not self._file_system: return True if self._file_system.IsHFS(): attribute_type = getattr(self._tsk_attribute.info, 'type', None) return attribute_type in ( pytsk3.TSK_FS_ATTR_TYPE_HFS_DEFAULT, pytsk3.TSK_FS_ATTR_TYPE_HFS_DATA) if self._file_system.IsNTFS(): return not bool(self.name) return True
[ "def", "IsDefault", "(", "self", ")", ":", "if", "not", "self", ".", "_tsk_attribute", "or", "not", "self", ".", "_file_system", ":", "return", "True", "if", "self", ".", "_file_system", ".", "IsHFS", "(", ")", ":", "attribute_type", "=", "getattr", "(",...
Determines if the data stream is the default data stream. Returns: bool: True if the data stream is the default data stream, false if not.
[ "Determines", "if", "the", "data", "stream", "is", "the", "default", "data", "stream", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L226-L243
train
208,357
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
TSKFileEntry._GetTimeValue
def _GetTimeValue(self, name): """Retrieves a date and time value. Args: name (str): name of the date and time value, for example "atime" or "mtime". Returns: dfdatetime.DateTimeValues: date and time value or None if not available. """ timestamp = getattr(self._tsk_file.info.meta, name, None) if self._file_system_type in self._TSK_HAS_NANO_FS_TYPES: name_fragment = '{0:s}_nano'.format(name) fraction_of_second = getattr( self._tsk_file.info.meta, name_fragment, None) else: fraction_of_second = None return TSKTime(timestamp=timestamp, fraction_of_second=fraction_of_second)
python
def _GetTimeValue(self, name): """Retrieves a date and time value. Args: name (str): name of the date and time value, for example "atime" or "mtime". Returns: dfdatetime.DateTimeValues: date and time value or None if not available. """ timestamp = getattr(self._tsk_file.info.meta, name, None) if self._file_system_type in self._TSK_HAS_NANO_FS_TYPES: name_fragment = '{0:s}_nano'.format(name) fraction_of_second = getattr( self._tsk_file.info.meta, name_fragment, None) else: fraction_of_second = None return TSKTime(timestamp=timestamp, fraction_of_second=fraction_of_second)
[ "def", "_GetTimeValue", "(", "self", ",", "name", ")", ":", "timestamp", "=", "getattr", "(", "self", ".", "_tsk_file", ".", "info", ".", "meta", ",", "name", ",", "None", ")", "if", "self", ".", "_file_system_type", "in", "self", ".", "_TSK_HAS_NANO_FS_...
Retrieves a date and time value. Args: name (str): name of the date and time value, for example "atime" or "mtime". Returns: dfdatetime.DateTimeValues: date and time value or None if not available.
[ "Retrieves", "a", "date", "and", "time", "value", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L650-L669
train
208,358
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
TSKFileEntry._TSKFileTimeCopyToStatTimeTuple
def _TSKFileTimeCopyToStatTimeTuple(self, tsk_file, time_value): """Copies a SleuthKit file object time value to a stat timestamp tuple. Args: tsk_file (pytsk3.File): TSK file. time_value (str): name of the time value. Returns: tuple[int, int]: number of seconds since 1970-01-01 00:00:00 and fraction of second in 100 nano seconds intervals. The number of seconds is None on error, or if the file system does not include the requested timestamp. The fraction of second is None on error, or if the file system does not support sub-second precision. Raises: BackEndError: if the TSK File .info, .info.meta or info.fs_info attribute is missing. """ if (not tsk_file or not tsk_file.info or not tsk_file.info.meta or not tsk_file.info.fs_info): raise errors.BackEndError( 'Missing TSK File .info, .info.meta. or .info.fs_info') stat_time = getattr(tsk_file.info.meta, time_value, None) stat_time_nano = None if self._file_system_type in self._TSK_HAS_NANO_FS_TYPES: time_value_nano = '{0:s}_nano'.format(time_value) stat_time_nano = getattr(tsk_file.info.meta, time_value_nano, None) # Sleuthkit 4.2.0 switched from 100 nano seconds precision to # 1 nano seconds precision. if stat_time_nano is not None and pytsk3.TSK_VERSION_NUM >= 0x040200ff: stat_time_nano /= 100 return stat_time, stat_time_nano
python
def _TSKFileTimeCopyToStatTimeTuple(self, tsk_file, time_value): """Copies a SleuthKit file object time value to a stat timestamp tuple. Args: tsk_file (pytsk3.File): TSK file. time_value (str): name of the time value. Returns: tuple[int, int]: number of seconds since 1970-01-01 00:00:00 and fraction of second in 100 nano seconds intervals. The number of seconds is None on error, or if the file system does not include the requested timestamp. The fraction of second is None on error, or if the file system does not support sub-second precision. Raises: BackEndError: if the TSK File .info, .info.meta or info.fs_info attribute is missing. """ if (not tsk_file or not tsk_file.info or not tsk_file.info.meta or not tsk_file.info.fs_info): raise errors.BackEndError( 'Missing TSK File .info, .info.meta. or .info.fs_info') stat_time = getattr(tsk_file.info.meta, time_value, None) stat_time_nano = None if self._file_system_type in self._TSK_HAS_NANO_FS_TYPES: time_value_nano = '{0:s}_nano'.format(time_value) stat_time_nano = getattr(tsk_file.info.meta, time_value_nano, None) # Sleuthkit 4.2.0 switched from 100 nano seconds precision to # 1 nano seconds precision. if stat_time_nano is not None and pytsk3.TSK_VERSION_NUM >= 0x040200ff: stat_time_nano /= 100 return stat_time, stat_time_nano
[ "def", "_TSKFileTimeCopyToStatTimeTuple", "(", "self", ",", "tsk_file", ",", "time_value", ")", ":", "if", "(", "not", "tsk_file", "or", "not", "tsk_file", ".", "info", "or", "not", "tsk_file", ".", "info", ".", "meta", "or", "not", "tsk_file", ".", "info"...
Copies a SleuthKit file object time value to a stat timestamp tuple. Args: tsk_file (pytsk3.File): TSK file. time_value (str): name of the time value. Returns: tuple[int, int]: number of seconds since 1970-01-01 00:00:00 and fraction of second in 100 nano seconds intervals. The number of seconds is None on error, or if the file system does not include the requested timestamp. The fraction of second is None on error, or if the file system does not support sub-second precision. Raises: BackEndError: if the TSK File .info, .info.meta or info.fs_info attribute is missing.
[ "Copies", "a", "SleuthKit", "file", "object", "time", "value", "to", "a", "stat", "timestamp", "tuple", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L671-L705
train
208,359
log2timeline/dfvfs
dfvfs/lib/fvde.py
FVDEVolumeOpen
def FVDEVolumeOpen(fvde_volume, path_spec, file_object, key_chain): """Opens the FVDE volume using the path specification. Args: fvde_volume (pyfvde.volume): FVDE volume. path_spec (PathSpec): path specification. file_object (FileIO): file-like object. key_chain (KeyChain): key chain. """ encrypted_root_plist = key_chain.GetCredential( path_spec, 'encrypted_root_plist') if encrypted_root_plist: fvde_volume.read_encrypted_root_plist(encrypted_root_plist) password = key_chain.GetCredential(path_spec, 'password') if password: fvde_volume.set_password(password) recovery_password = key_chain.GetCredential(path_spec, 'recovery_password') if recovery_password: fvde_volume.set_recovery_password(recovery_password) fvde_volume.open_file_object(file_object)
python
def FVDEVolumeOpen(fvde_volume, path_spec, file_object, key_chain): """Opens the FVDE volume using the path specification. Args: fvde_volume (pyfvde.volume): FVDE volume. path_spec (PathSpec): path specification. file_object (FileIO): file-like object. key_chain (KeyChain): key chain. """ encrypted_root_plist = key_chain.GetCredential( path_spec, 'encrypted_root_plist') if encrypted_root_plist: fvde_volume.read_encrypted_root_plist(encrypted_root_plist) password = key_chain.GetCredential(path_spec, 'password') if password: fvde_volume.set_password(password) recovery_password = key_chain.GetCredential(path_spec, 'recovery_password') if recovery_password: fvde_volume.set_recovery_password(recovery_password) fvde_volume.open_file_object(file_object)
[ "def", "FVDEVolumeOpen", "(", "fvde_volume", ",", "path_spec", ",", "file_object", ",", "key_chain", ")", ":", "encrypted_root_plist", "=", "key_chain", ".", "GetCredential", "(", "path_spec", ",", "'encrypted_root_plist'", ")", "if", "encrypted_root_plist", ":", "f...
Opens the FVDE volume using the path specification. Args: fvde_volume (pyfvde.volume): FVDE volume. path_spec (PathSpec): path specification. file_object (FileIO): file-like object. key_chain (KeyChain): key chain.
[ "Opens", "the", "FVDE", "volume", "using", "the", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/fvde.py#L7-L29
train
208,360
log2timeline/dfvfs
dfvfs/lib/vshadow.py
VShadowPathSpecGetStoreIndex
def VShadowPathSpecGetStoreIndex(path_spec): """Retrieves the store index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: store index or None if not available. """ store_index = getattr(path_spec, 'store_index', None) if store_index is None: location = getattr(path_spec, 'location', None) if location is None or not location.startswith('/vss'): return None store_index = None try: store_index = int(location[4:], 10) - 1 except (TypeError, ValueError): pass if store_index is None or store_index < 0: return None return store_index
python
def VShadowPathSpecGetStoreIndex(path_spec): """Retrieves the store index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: store index or None if not available. """ store_index = getattr(path_spec, 'store_index', None) if store_index is None: location = getattr(path_spec, 'location', None) if location is None or not location.startswith('/vss'): return None store_index = None try: store_index = int(location[4:], 10) - 1 except (TypeError, ValueError): pass if store_index is None or store_index < 0: return None return store_index
[ "def", "VShadowPathSpecGetStoreIndex", "(", "path_spec", ")", ":", "store_index", "=", "getattr", "(", "path_spec", ",", "'store_index'", ",", "None", ")", "if", "store_index", "is", "None", ":", "location", "=", "getattr", "(", "path_spec", ",", "'location'", ...
Retrieves the store index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: store index or None if not available.
[ "Retrieves", "the", "store", "index", "from", "the", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/vshadow.py#L7-L33
train
208,361
log2timeline/dfvfs
dfvfs/file_io/gzip_file_io.py
GzipFile._GetMemberForOffset
def _GetMemberForOffset(self, offset): """Finds the member whose data includes the provided offset. Args: offset (int): offset in the uncompressed data to find the containing member for. Returns: gzipfile.GzipMember: gzip file member or None if not available. Raises: ValueError: if the provided offset is outside of the bounds of the uncompressed data. """ if offset < 0 or offset >= self.uncompressed_data_size: raise ValueError('Offset {0:d} is larger than file size {1:d}.'.format( offset, self.uncompressed_data_size)) for end_offset, member in iter(self._members_by_end_offset.items()): if offset < end_offset: return member return None
python
def _GetMemberForOffset(self, offset): """Finds the member whose data includes the provided offset. Args: offset (int): offset in the uncompressed data to find the containing member for. Returns: gzipfile.GzipMember: gzip file member or None if not available. Raises: ValueError: if the provided offset is outside of the bounds of the uncompressed data. """ if offset < 0 or offset >= self.uncompressed_data_size: raise ValueError('Offset {0:d} is larger than file size {1:d}.'.format( offset, self.uncompressed_data_size)) for end_offset, member in iter(self._members_by_end_offset.items()): if offset < end_offset: return member return None
[ "def", "_GetMemberForOffset", "(", "self", ",", "offset", ")", ":", "if", "offset", "<", "0", "or", "offset", ">=", "self", ".", "uncompressed_data_size", ":", "raise", "ValueError", "(", "'Offset {0:d} is larger than file size {1:d}.'", ".", "format", "(", "offse...
Finds the member whose data includes the provided offset. Args: offset (int): offset in the uncompressed data to find the containing member for. Returns: gzipfile.GzipMember: gzip file member or None if not available. Raises: ValueError: if the provided offset is outside of the bounds of the uncompressed data.
[ "Finds", "the", "member", "whose", "data", "includes", "the", "provided", "offset", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/gzip_file_io.py#L66-L88
train
208,362
log2timeline/dfvfs
dfvfs/file_io/gzip_file_io.py
GzipFile.read
def read(self, size=None): """Reads a byte string from the gzip file at the current offset. The function will read a byte string up to the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed. """ data = b'' while ((size and len(data) < size) and self._current_offset < self.uncompressed_data_size): member = self._GetMemberForOffset(self._current_offset) member_offset = self._current_offset - member.uncompressed_data_offset data_read = member.ReadAtOffset(member_offset, size) if data_read: self._current_offset += len(data_read) data = b''.join([data, data_read]) return data
python
def read(self, size=None): """Reads a byte string from the gzip file at the current offset. The function will read a byte string up to the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed. """ data = b'' while ((size and len(data) < size) and self._current_offset < self.uncompressed_data_size): member = self._GetMemberForOffset(self._current_offset) member_offset = self._current_offset - member.uncompressed_data_offset data_read = member.ReadAtOffset(member_offset, size) if data_read: self._current_offset += len(data_read) data = b''.join([data, data_read]) return data
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "data", "=", "b''", "while", "(", "(", "size", "and", "len", "(", "data", ")", "<", "size", ")", "and", "self", ".", "_current_offset", "<", "self", ".", "uncompressed_data_size", ")", ...
Reads a byte string from the gzip file at the current offset. The function will read a byte string up to the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed.
[ "Reads", "a", "byte", "string", "from", "the", "gzip", "file", "at", "the", "current", "offset", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/gzip_file_io.py#L117-L144
train
208,363
log2timeline/dfvfs
dfvfs/vfs/data_range_file_entry.py
DataRangeFileEntry._GetStat
def _GetStat(self): """Retrieves a stat object. Returns: VFSStat: a stat object. Raises: BackEndError: when the encoded stream is missing. """ stat_object = vfs_stat.VFSStat() # File data stat information. stat_object.size = self.path_spec.range_size # File entry type stat information. stat_object.type = stat_object.TYPE_FILE return stat_object
python
def _GetStat(self): """Retrieves a stat object. Returns: VFSStat: a stat object. Raises: BackEndError: when the encoded stream is missing. """ stat_object = vfs_stat.VFSStat() # File data stat information. stat_object.size = self.path_spec.range_size # File entry type stat information. stat_object.type = stat_object.TYPE_FILE return stat_object
[ "def", "_GetStat", "(", "self", ")", ":", "stat_object", "=", "vfs_stat", ".", "VFSStat", "(", ")", "# File data stat information.", "stat_object", ".", "size", "=", "self", ".", "path_spec", ".", "range_size", "# File entry type stat information.", "stat_object", "...
Retrieves a stat object. Returns: VFSStat: a stat object. Raises: BackEndError: when the encoded stream is missing.
[ "Retrieves", "a", "stat", "object", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/data_range_file_entry.py#L16-L33
train
208,364
log2timeline/dfvfs
dfvfs/path/path_spec.py
PathSpec._GetComparable
def _GetComparable(self, sub_comparable_string=''): """Retrieves the comparable representation. This is a convenience function for constructing comparables. Args: sub_comparable_string (str): sub comparable string. Returns: str: comparable representation of the path specification. """ string_parts = [] string_parts.append(getattr(self.parent, 'comparable', '')) string_parts.append('type: {0:s}'.format(self.type_indicator)) if sub_comparable_string: string_parts.append(', {0:s}'.format(sub_comparable_string)) string_parts.append('\n') return ''.join(string_parts)
python
def _GetComparable(self, sub_comparable_string=''): """Retrieves the comparable representation. This is a convenience function for constructing comparables. Args: sub_comparable_string (str): sub comparable string. Returns: str: comparable representation of the path specification. """ string_parts = [] string_parts.append(getattr(self.parent, 'comparable', '')) string_parts.append('type: {0:s}'.format(self.type_indicator)) if sub_comparable_string: string_parts.append(', {0:s}'.format(sub_comparable_string)) string_parts.append('\n') return ''.join(string_parts)
[ "def", "_GetComparable", "(", "self", ",", "sub_comparable_string", "=", "''", ")", ":", "string_parts", "=", "[", "]", "string_parts", ".", "append", "(", "getattr", "(", "self", ".", "parent", ",", "'comparable'", ",", "''", ")", ")", "string_parts", "."...
Retrieves the comparable representation. This is a convenience function for constructing comparables. Args: sub_comparable_string (str): sub comparable string. Returns: str: comparable representation of the path specification.
[ "Retrieves", "the", "comparable", "representation", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/path/path_spec.py#L50-L70
train
208,365
log2timeline/dfvfs
dfvfs/path/path_spec.py
PathSpec.CopyToDict
def CopyToDict(self): """Copies the path specification to a dictionary. Returns: dict[str, object]: path specification attributes. """ path_spec_dict = {} for attribute_name, attribute_value in iter(self.__dict__.items()): if attribute_value is None: continue if attribute_name == 'parent': attribute_value = attribute_value.CopyToDict() path_spec_dict[attribute_name] = attribute_value return path_spec_dict
python
def CopyToDict(self): """Copies the path specification to a dictionary. Returns: dict[str, object]: path specification attributes. """ path_spec_dict = {} for attribute_name, attribute_value in iter(self.__dict__.items()): if attribute_value is None: continue if attribute_name == 'parent': attribute_value = attribute_value.CopyToDict() path_spec_dict[attribute_name] = attribute_value return path_spec_dict
[ "def", "CopyToDict", "(", "self", ")", ":", "path_spec_dict", "=", "{", "}", "for", "attribute_name", ",", "attribute_value", "in", "iter", "(", "self", ".", "__dict__", ".", "items", "(", ")", ")", ":", "if", "attribute_value", "is", "None", ":", "conti...
Copies the path specification to a dictionary. Returns: dict[str, object]: path specification attributes.
[ "Copies", "the", "path", "specification", "to", "a", "dictionary", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/path/path_spec.py#L83-L99
train
208,366
log2timeline/dfvfs
dfvfs/mount/manager.py
MountPointManager.DeregisterMountPoint
def DeregisterMountPoint(cls, mount_point): """Deregisters a path specification mount point. Args: mount_point (str): mount point identifier. Raises: KeyError: if the corresponding mount point is not set. """ if mount_point not in cls._mount_points: raise KeyError('Mount point: {0:s} not set.'.format(mount_point)) del cls._mount_points[mount_point]
python
def DeregisterMountPoint(cls, mount_point): """Deregisters a path specification mount point. Args: mount_point (str): mount point identifier. Raises: KeyError: if the corresponding mount point is not set. """ if mount_point not in cls._mount_points: raise KeyError('Mount point: {0:s} not set.'.format(mount_point)) del cls._mount_points[mount_point]
[ "def", "DeregisterMountPoint", "(", "cls", ",", "mount_point", ")", ":", "if", "mount_point", "not", "in", "cls", ".", "_mount_points", ":", "raise", "KeyError", "(", "'Mount point: {0:s} not set.'", ".", "format", "(", "mount_point", ")", ")", "del", "cls", "...
Deregisters a path specification mount point. Args: mount_point (str): mount point identifier. Raises: KeyError: if the corresponding mount point is not set.
[ "Deregisters", "a", "path", "specification", "mount", "point", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/mount/manager.py#L33-L45
train
208,367
log2timeline/dfvfs
dfvfs/mount/manager.py
MountPointManager.RegisterMountPoint
def RegisterMountPoint(cls, mount_point, path_spec): """Registers a path specification mount point. Args: mount_point (str): mount point identifier. path_spec (PathSpec): path specification of the mount point. Raises: KeyError: if the corresponding mount point is already set. """ if mount_point in cls._mount_points: raise KeyError('Mount point: {0:s} already set.'.format(mount_point)) cls._mount_points[mount_point] = path_spec
python
def RegisterMountPoint(cls, mount_point, path_spec): """Registers a path specification mount point. Args: mount_point (str): mount point identifier. path_spec (PathSpec): path specification of the mount point. Raises: KeyError: if the corresponding mount point is already set. """ if mount_point in cls._mount_points: raise KeyError('Mount point: {0:s} already set.'.format(mount_point)) cls._mount_points[mount_point] = path_spec
[ "def", "RegisterMountPoint", "(", "cls", ",", "mount_point", ",", "path_spec", ")", ":", "if", "mount_point", "in", "cls", ".", "_mount_points", ":", "raise", "KeyError", "(", "'Mount point: {0:s} already set.'", ".", "format", "(", "mount_point", ")", ")", "cls...
Registers a path specification mount point. Args: mount_point (str): mount point identifier. path_spec (PathSpec): path specification of the mount point. Raises: KeyError: if the corresponding mount point is already set.
[ "Registers", "a", "path", "specification", "mount", "point", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/mount/manager.py#L61-L74
train
208,368
log2timeline/dfvfs
dfvfs/resolver_helpers/manager.py
ResolverHelperManager.DeregisterHelper
def DeregisterHelper(cls, resolver_helper): """Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is not set for the corresponding type indicator. """ if resolver_helper.type_indicator not in cls._resolver_helpers: raise KeyError( 'Resolver helper object not set for type indicator: {0:s}.'.format( resolver_helper.type_indicator)) del cls._resolver_helpers[resolver_helper.type_indicator]
python
def DeregisterHelper(cls, resolver_helper): """Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is not set for the corresponding type indicator. """ if resolver_helper.type_indicator not in cls._resolver_helpers: raise KeyError( 'Resolver helper object not set for type indicator: {0:s}.'.format( resolver_helper.type_indicator)) del cls._resolver_helpers[resolver_helper.type_indicator]
[ "def", "DeregisterHelper", "(", "cls", ",", "resolver_helper", ")", ":", "if", "resolver_helper", ".", "type_indicator", "not", "in", "cls", ".", "_resolver_helpers", ":", "raise", "KeyError", "(", "'Resolver helper object not set for type indicator: {0:s}.'", ".", "for...
Deregisters a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is not set for the corresponding type indicator.
[ "Deregisters", "a", "path", "specification", "resolver", "helper", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver_helpers/manager.py#L13-L28
train
208,369
log2timeline/dfvfs
dfvfs/resolver_helpers/manager.py
ResolverHelperManager.RegisterHelper
def RegisterHelper(cls, resolver_helper): """Registers a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is already set for the corresponding type indicator. """ if resolver_helper.type_indicator in cls._resolver_helpers: raise KeyError(( 'Resolver helper object already set for type indicator: ' '{0!s}.').format(resolver_helper.type_indicator)) cls._resolver_helpers[resolver_helper.type_indicator] = resolver_helper
python
def RegisterHelper(cls, resolver_helper): """Registers a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is already set for the corresponding type indicator. """ if resolver_helper.type_indicator in cls._resolver_helpers: raise KeyError(( 'Resolver helper object already set for type indicator: ' '{0!s}.').format(resolver_helper.type_indicator)) cls._resolver_helpers[resolver_helper.type_indicator] = resolver_helper
[ "def", "RegisterHelper", "(", "cls", ",", "resolver_helper", ")", ":", "if", "resolver_helper", ".", "type_indicator", "in", "cls", ".", "_resolver_helpers", ":", "raise", "KeyError", "(", "(", "'Resolver helper object already set for type indicator: '", "'{0!s}.'", ")"...
Registers a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is already set for the corresponding type indicator.
[ "Registers", "a", "path", "specification", "resolver", "helper", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver_helpers/manager.py#L52-L67
train
208,370
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.GetDataStream
def GetDataStream(self, name, case_sensitive=True): """Retrieves a data stream by name. Args: name (str): name of the data stream. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: DataStream: a data stream or None if not available. Raises: ValueError: if the name is not string. """ if not isinstance(name, py2to3.STRING_TYPES): raise ValueError('Name is not a string.') name_lower = name.lower() matching_data_stream = None for data_stream in self._GetDataStreams(): if data_stream.name == name: return data_stream if not case_sensitive and data_stream.name.lower() == name_lower: if not matching_data_stream: matching_data_stream = data_stream return matching_data_stream
python
def GetDataStream(self, name, case_sensitive=True): """Retrieves a data stream by name. Args: name (str): name of the data stream. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: DataStream: a data stream or None if not available. Raises: ValueError: if the name is not string. """ if not isinstance(name, py2to3.STRING_TYPES): raise ValueError('Name is not a string.') name_lower = name.lower() matching_data_stream = None for data_stream in self._GetDataStreams(): if data_stream.name == name: return data_stream if not case_sensitive and data_stream.name.lower() == name_lower: if not matching_data_stream: matching_data_stream = data_stream return matching_data_stream
[ "def", "GetDataStream", "(", "self", ",", "name", ",", "case_sensitive", "=", "True", ")", ":", "if", "not", "isinstance", "(", "name", ",", "py2to3", ".", "STRING_TYPES", ")", ":", "raise", "ValueError", "(", "'Name is not a string.'", ")", "name_lower", "=...
Retrieves a data stream by name. Args: name (str): name of the data stream. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: DataStream: a data stream or None if not available. Raises: ValueError: if the name is not string.
[ "Retrieves", "a", "data", "stream", "by", "name", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L326-L353
train
208,371
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.GetSubFileEntryByName
def GetSubFileEntryByName(self, name, case_sensitive=True): """Retrieves a sub file entry by name. Args: name (str): name of the file entry. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: FileEntry: a file entry or None if not available. """ name_lower = name.lower() matching_sub_file_entry = None for sub_file_entry in self.sub_file_entries: if sub_file_entry.name == name: return sub_file_entry if not case_sensitive and sub_file_entry.name.lower() == name_lower: if not matching_sub_file_entry: matching_sub_file_entry = sub_file_entry return matching_sub_file_entry
python
def GetSubFileEntryByName(self, name, case_sensitive=True): """Retrieves a sub file entry by name. Args: name (str): name of the file entry. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: FileEntry: a file entry or None if not available. """ name_lower = name.lower() matching_sub_file_entry = None for sub_file_entry in self.sub_file_entries: if sub_file_entry.name == name: return sub_file_entry if not case_sensitive and sub_file_entry.name.lower() == name_lower: if not matching_sub_file_entry: matching_sub_file_entry = sub_file_entry return matching_sub_file_entry
[ "def", "GetSubFileEntryByName", "(", "self", ",", "name", ",", "case_sensitive", "=", "True", ")", ":", "name_lower", "=", "name", ".", "lower", "(", ")", "matching_sub_file_entry", "=", "None", "for", "sub_file_entry", "in", "self", ".", "sub_file_entries", "...
Retrieves a sub file entry by name. Args: name (str): name of the file entry. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: FileEntry: a file entry or None if not available.
[ "Retrieves", "a", "sub", "file", "entry", "by", "name", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L395-L416
train
208,372
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.HasDataStream
def HasDataStream(self, name, case_sensitive=True): """Determines if the file entry has specific data stream. Args: name (str): name of the data stream. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: bool: True if the file entry has the data stream. Raises: ValueError: if the name is not string. """ if not isinstance(name, py2to3.STRING_TYPES): raise ValueError('Name is not a string.') name_lower = name.lower() for data_stream in self._GetDataStreams(): if data_stream.name == name: return True if not case_sensitive and data_stream.name.lower() == name_lower: return True return False
python
def HasDataStream(self, name, case_sensitive=True): """Determines if the file entry has specific data stream. Args: name (str): name of the data stream. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: bool: True if the file entry has the data stream. Raises: ValueError: if the name is not string. """ if not isinstance(name, py2to3.STRING_TYPES): raise ValueError('Name is not a string.') name_lower = name.lower() for data_stream in self._GetDataStreams(): if data_stream.name == name: return True if not case_sensitive and data_stream.name.lower() == name_lower: return True return False
[ "def", "HasDataStream", "(", "self", ",", "name", ",", "case_sensitive", "=", "True", ")", ":", "if", "not", "isinstance", "(", "name", ",", "py2to3", ".", "STRING_TYPES", ")", ":", "raise", "ValueError", "(", "'Name is not a string.'", ")", "name_lower", "=...
Determines if the file entry has specific data stream. Args: name (str): name of the data stream. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: bool: True if the file entry has the data stream. Raises: ValueError: if the name is not string.
[ "Determines", "if", "the", "file", "entry", "has", "specific", "data", "stream", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L428-L453
train
208,373
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.IsAllocated
def IsAllocated(self): """Determines if the file entry is allocated. Returns: bool: True if the file entry is allocated. """ if self._stat_object is None: self._stat_object = self._GetStat() return self._stat_object and self._stat_object.is_allocated
python
def IsAllocated(self): """Determines if the file entry is allocated. Returns: bool: True if the file entry is allocated. """ if self._stat_object is None: self._stat_object = self._GetStat() return self._stat_object and self._stat_object.is_allocated
[ "def", "IsAllocated", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "return", "self", ".", "_stat_object", "and", "self", ".", "_stat_object", ".", "is_al...
Determines if the file entry is allocated. Returns: bool: True if the file entry is allocated.
[ "Determines", "if", "the", "file", "entry", "is", "allocated", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L463-L471
train
208,374
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.IsDevice
def IsDevice(self): """Determines if the file entry is a device. Returns: bool: True if the file entry is a device. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_DEVICE
python
def IsDevice(self): """Determines if the file entry is a device. Returns: bool: True if the file entry is a device. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_DEVICE
[ "def", "IsDevice", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type",...
Determines if the file entry is a device. Returns: bool: True if the file entry is a device.
[ "Determines", "if", "the", "file", "entry", "is", "a", "device", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L473-L483
train
208,375
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.IsDirectory
def IsDirectory(self): """Determines if the file entry is a directory. Returns: bool: True if the file entry is a directory. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_DIRECTORY
python
def IsDirectory(self): """Determines if the file entry is a directory. Returns: bool: True if the file entry is a directory. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_DIRECTORY
[ "def", "IsDirectory", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_typ...
Determines if the file entry is a directory. Returns: bool: True if the file entry is a directory.
[ "Determines", "if", "the", "file", "entry", "is", "a", "directory", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L485-L495
train
208,376
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.IsFile
def IsFile(self): """Determines if the file entry is a file. Returns: bool: True if the file entry is a file. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_FILE
python
def IsFile(self): """Determines if the file entry is a file. Returns: bool: True if the file entry is a file. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_FILE
[ "def", "IsFile", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type", ...
Determines if the file entry is a file. Returns: bool: True if the file entry is a file.
[ "Determines", "if", "the", "file", "entry", "is", "a", "file", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L497-L507
train
208,377
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.IsLink
def IsLink(self): """Determines if the file entry is a link. Returns: bool: True if the file entry is a link. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_LINK
python
def IsLink(self): """Determines if the file entry is a link. Returns: bool: True if the file entry is a link. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_LINK
[ "def", "IsLink", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type", ...
Determines if the file entry is a link. Returns: bool: True if the file entry is a link.
[ "Determines", "if", "the", "file", "entry", "is", "a", "link", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L509-L519
train
208,378
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.IsPipe
def IsPipe(self): """Determines if the file entry is a pipe. Returns: bool: True if the file entry is a pipe. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_PIPE
python
def IsPipe(self): """Determines if the file entry is a pipe. Returns: bool: True if the file entry is a pipe. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_PIPE
[ "def", "IsPipe", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type", ...
Determines if the file entry is a pipe. Returns: bool: True if the file entry is a pipe.
[ "Determines", "if", "the", "file", "entry", "is", "a", "pipe", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L521-L531
train
208,379
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
FileEntry.IsSocket
def IsSocket(self): """Determines if the file entry is a socket. Returns: bool: True if the file entry is a socket. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_SOCKET
python
def IsSocket(self): """Determines if the file entry is a socket. Returns: bool: True if the file entry is a socket. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entry_type == definitions.FILE_ENTRY_TYPE_SOCKET
[ "def", "IsSocket", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type",...
Determines if the file entry is a socket. Returns: bool: True if the file entry is a socket.
[ "Determines", "if", "the", "file", "entry", "is", "a", "socket", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L541-L551
train
208,380
log2timeline/dfvfs
dfvfs/volume/tsk_volume_system.py
TSKVolumeSystem.Open
def Open(self, path_spec): """Opens a volume defined by path specification. Args: path_spec (PathSpec): a path specification. Raises: VolumeSystemError: if the TSK partition virtual file system could not be resolved. """ self._file_system = resolver.Resolver.OpenFileSystem(path_spec) if self._file_system is None: raise errors.VolumeSystemError('Unable to resolve path specification.') type_indicator = self._file_system.type_indicator if type_indicator != definitions.TYPE_INDICATOR_TSK_PARTITION: raise errors.VolumeSystemError('Unsupported type indicator.')
python
def Open(self, path_spec): """Opens a volume defined by path specification. Args: path_spec (PathSpec): a path specification. Raises: VolumeSystemError: if the TSK partition virtual file system could not be resolved. """ self._file_system = resolver.Resolver.OpenFileSystem(path_spec) if self._file_system is None: raise errors.VolumeSystemError('Unable to resolve path specification.') type_indicator = self._file_system.type_indicator if type_indicator != definitions.TYPE_INDICATOR_TSK_PARTITION: raise errors.VolumeSystemError('Unsupported type indicator.')
[ "def", "Open", "(", "self", ",", "path_spec", ")", ":", "self", ".", "_file_system", "=", "resolver", ".", "Resolver", ".", "OpenFileSystem", "(", "path_spec", ")", "if", "self", ".", "_file_system", "is", "None", ":", "raise", "errors", ".", "VolumeSystem...
Opens a volume defined by path specification. Args: path_spec (PathSpec): a path specification. Raises: VolumeSystemError: if the TSK partition virtual file system could not be resolved.
[ "Opens", "a", "volume", "defined", "by", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/tsk_volume_system.py#L91-L107
train
208,381
log2timeline/dfvfs
dfvfs/vfs/lvm_file_system.py
LVMFileSystem.GetLVMLogicalVolumeByPathSpec
def GetLVMLogicalVolumeByPathSpec(self, path_spec): """Retrieves a LVM logical volume for a path specification. Args: path_spec (PathSpec): path specification. Returns: pyvslvm.logical_volume: a LVM logical volume or None if not available. """ volume_index = lvm.LVMPathSpecGetVolumeIndex(path_spec) if volume_index is None: return None return self._vslvm_volume_group.get_logical_volume(volume_index)
python
def GetLVMLogicalVolumeByPathSpec(self, path_spec): """Retrieves a LVM logical volume for a path specification. Args: path_spec (PathSpec): path specification. Returns: pyvslvm.logical_volume: a LVM logical volume or None if not available. """ volume_index = lvm.LVMPathSpecGetVolumeIndex(path_spec) if volume_index is None: return None return self._vslvm_volume_group.get_logical_volume(volume_index)
[ "def", "GetLVMLogicalVolumeByPathSpec", "(", "self", ",", "path_spec", ")", ":", "volume_index", "=", "lvm", ".", "LVMPathSpecGetVolumeIndex", "(", "path_spec", ")", "if", "volume_index", "is", "None", ":", "return", "None", "return", "self", ".", "_vslvm_volume_g...
Retrieves a LVM logical volume for a path specification. Args: path_spec (PathSpec): path specification. Returns: pyvslvm.logical_volume: a LVM logical volume or None if not available.
[ "Retrieves", "a", "LVM", "logical", "volume", "for", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/lvm_file_system.py#L130-L142
train
208,382
log2timeline/dfvfs
dfvfs/credentials/keychain.py
KeyChain.ExtractCredentialsFromPathSpec
def ExtractCredentialsFromPathSpec(self, path_spec): """Extracts credentials from a path specification. Args: path_spec (PathSpec): path specification to extract credentials from. """ credentials = manager.CredentialsManager.GetCredentials(path_spec) for identifier in credentials.CREDENTIALS: value = getattr(path_spec, identifier, None) if value is None: continue self.SetCredential(path_spec, identifier, value)
python
def ExtractCredentialsFromPathSpec(self, path_spec): """Extracts credentials from a path specification. Args: path_spec (PathSpec): path specification to extract credentials from. """ credentials = manager.CredentialsManager.GetCredentials(path_spec) for identifier in credentials.CREDENTIALS: value = getattr(path_spec, identifier, None) if value is None: continue self.SetCredential(path_spec, identifier, value)
[ "def", "ExtractCredentialsFromPathSpec", "(", "self", ",", "path_spec", ")", ":", "credentials", "=", "manager", ".", "CredentialsManager", ".", "GetCredentials", "(", "path_spec", ")", "for", "identifier", "in", "credentials", ".", "CREDENTIALS", ":", "value", "=...
Extracts credentials from a path specification. Args: path_spec (PathSpec): path specification to extract credentials from.
[ "Extracts", "credentials", "from", "a", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/credentials/keychain.py#L26-L38
train
208,383
log2timeline/dfvfs
dfvfs/credentials/keychain.py
KeyChain.GetCredential
def GetCredential(self, path_spec, identifier): """Retrieves a specific credential from the key chain. Args: path_spec (PathSpec): path specification. identifier (str): credential identifier. Returns: object: credential or None if the credential for the path specification is not set. """ credentials = self._credentials_per_path_spec.get(path_spec.comparable, {}) return credentials.get(identifier, None)
python
def GetCredential(self, path_spec, identifier): """Retrieves a specific credential from the key chain. Args: path_spec (PathSpec): path specification. identifier (str): credential identifier. Returns: object: credential or None if the credential for the path specification is not set. """ credentials = self._credentials_per_path_spec.get(path_spec.comparable, {}) return credentials.get(identifier, None)
[ "def", "GetCredential", "(", "self", ",", "path_spec", ",", "identifier", ")", ":", "credentials", "=", "self", ".", "_credentials_per_path_spec", ".", "get", "(", "path_spec", ".", "comparable", ",", "{", "}", ")", "return", "credentials", ".", "get", "(", ...
Retrieves a specific credential from the key chain. Args: path_spec (PathSpec): path specification. identifier (str): credential identifier. Returns: object: credential or None if the credential for the path specification is not set.
[ "Retrieves", "a", "specific", "credential", "from", "the", "key", "chain", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/credentials/keychain.py#L40-L52
train
208,384
log2timeline/dfvfs
dfvfs/credentials/keychain.py
KeyChain.SetCredential
def SetCredential(self, path_spec, identifier, data): """Sets a specific credential for the path specification. Args: path_spec (PathSpec): path specification. identifier (str): credential identifier. data (object): credential data. Raises: KeyError: if the credential is not supported by the path specification type. """ supported_credentials = manager.CredentialsManager.GetCredentials(path_spec) if identifier not in supported_credentials.CREDENTIALS: raise KeyError(( 'Unsuppored credential: {0:s} for path specification type: ' '{1:s}').format(identifier, path_spec.type_indicator)) credentials = self._credentials_per_path_spec.get(path_spec.comparable, {}) credentials[identifier] = data self._credentials_per_path_spec[path_spec.comparable] = credentials
python
def SetCredential(self, path_spec, identifier, data): """Sets a specific credential for the path specification. Args: path_spec (PathSpec): path specification. identifier (str): credential identifier. data (object): credential data. Raises: KeyError: if the credential is not supported by the path specification type. """ supported_credentials = manager.CredentialsManager.GetCredentials(path_spec) if identifier not in supported_credentials.CREDENTIALS: raise KeyError(( 'Unsuppored credential: {0:s} for path specification type: ' '{1:s}').format(identifier, path_spec.type_indicator)) credentials = self._credentials_per_path_spec.get(path_spec.comparable, {}) credentials[identifier] = data self._credentials_per_path_spec[path_spec.comparable] = credentials
[ "def", "SetCredential", "(", "self", ",", "path_spec", ",", "identifier", ",", "data", ")", ":", "supported_credentials", "=", "manager", ".", "CredentialsManager", ".", "GetCredentials", "(", "path_spec", ")", "if", "identifier", "not", "in", "supported_credentia...
Sets a specific credential for the path specification. Args: path_spec (PathSpec): path specification. identifier (str): credential identifier. data (object): credential data. Raises: KeyError: if the credential is not supported by the path specification type.
[ "Sets", "a", "specific", "credential", "for", "the", "path", "specification", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/credentials/keychain.py#L65-L86
train
208,385
log2timeline/dfvfs
dfvfs/lib/ewf.py
EWFGlobPathSpec
def EWFGlobPathSpec(file_system, path_spec): """Globs for path specifications according to the EWF naming schema. Args: file_system (FileSystem): file system. path_spec (PathSpec): path specification. Returns: list[PathSpec]: path specifications that match the glob. Raises: PathSpecError: if the path specification is invalid. RuntimeError: if the maximum number of supported segment files is reached. """ if not path_spec.HasParent(): raise errors.PathSpecError( 'Unsupported path specification without parent.') parent_path_spec = path_spec.parent parent_location = getattr(parent_path_spec, 'location', None) if not parent_location: raise errors.PathSpecError( 'Unsupported parent path specification without location.') parent_location, _, segment_extension = parent_location.rpartition('.') segment_extension_start = segment_extension[0] segment_extension_length = len(segment_extension) if (segment_extension_length not in [3, 4] or not segment_extension.endswith('01') or ( segment_extension_length == 3 and segment_extension_start not in ['E', 'e', 's']) or ( segment_extension_length == 4 and not segment_extension.startswith('Ex'))): raise errors.PathSpecError(( 'Unsupported parent path specification invalid segment file ' 'extension: {0:s}').format(segment_extension)) segment_number = 1 segment_files = [] while True: segment_location = '{0:s}.{1:s}'.format(parent_location, segment_extension) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec) kwargs['location'] = segment_location if parent_path_spec.parent is not None: kwargs['parent'] = parent_path_spec.parent segment_path_spec = path_spec_factory.Factory.NewPathSpec( parent_path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(segment_path_spec): break segment_files.append(segment_path_spec) segment_number += 1 if segment_number <= 99: if segment_extension_length == 3: segment_extension = '{0:s}{1:02d}'.format( segment_extension_start, segment_number) elif segment_extension_length == 4: segment_extension = '{0:s}x{1:02d}'.format( segment_extension_start, segment_number) else: segment_index = segment_number - 100 if segment_extension_start in ['e', 's']: letter_offset = ord('a') else: letter_offset = ord('A') segment_index, remainder = divmod(segment_index, 26) third_letter = chr(letter_offset + remainder) segment_index, remainder = divmod(segment_index, 26) second_letter = chr(letter_offset + remainder) first_letter = chr(ord(segment_extension_start) + segment_index) if first_letter in ['[', '{']: raise RuntimeError('Unsupported number of segment files.') if segment_extension_length == 3: segment_extension = '{0:s}{1:s}{2:s}'.format( first_letter, second_letter, third_letter) elif segment_extension_length == 4: segment_extension = '{0:s}x{1:s}{2:s}'.format( first_letter, second_letter, third_letter) return segment_files
python
def EWFGlobPathSpec(file_system, path_spec): """Globs for path specifications according to the EWF naming schema. Args: file_system (FileSystem): file system. path_spec (PathSpec): path specification. Returns: list[PathSpec]: path specifications that match the glob. Raises: PathSpecError: if the path specification is invalid. RuntimeError: if the maximum number of supported segment files is reached. """ if not path_spec.HasParent(): raise errors.PathSpecError( 'Unsupported path specification without parent.') parent_path_spec = path_spec.parent parent_location = getattr(parent_path_spec, 'location', None) if not parent_location: raise errors.PathSpecError( 'Unsupported parent path specification without location.') parent_location, _, segment_extension = parent_location.rpartition('.') segment_extension_start = segment_extension[0] segment_extension_length = len(segment_extension) if (segment_extension_length not in [3, 4] or not segment_extension.endswith('01') or ( segment_extension_length == 3 and segment_extension_start not in ['E', 'e', 's']) or ( segment_extension_length == 4 and not segment_extension.startswith('Ex'))): raise errors.PathSpecError(( 'Unsupported parent path specification invalid segment file ' 'extension: {0:s}').format(segment_extension)) segment_number = 1 segment_files = [] while True: segment_location = '{0:s}.{1:s}'.format(parent_location, segment_extension) # Note that we don't want to set the keyword arguments when not used # because the path specification base class will check for unused # keyword arguments and raise. kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec) kwargs['location'] = segment_location if parent_path_spec.parent is not None: kwargs['parent'] = parent_path_spec.parent segment_path_spec = path_spec_factory.Factory.NewPathSpec( parent_path_spec.type_indicator, **kwargs) if not file_system.FileEntryExistsByPathSpec(segment_path_spec): break segment_files.append(segment_path_spec) segment_number += 1 if segment_number <= 99: if segment_extension_length == 3: segment_extension = '{0:s}{1:02d}'.format( segment_extension_start, segment_number) elif segment_extension_length == 4: segment_extension = '{0:s}x{1:02d}'.format( segment_extension_start, segment_number) else: segment_index = segment_number - 100 if segment_extension_start in ['e', 's']: letter_offset = ord('a') else: letter_offset = ord('A') segment_index, remainder = divmod(segment_index, 26) third_letter = chr(letter_offset + remainder) segment_index, remainder = divmod(segment_index, 26) second_letter = chr(letter_offset + remainder) first_letter = chr(ord(segment_extension_start) + segment_index) if first_letter in ['[', '{']: raise RuntimeError('Unsupported number of segment files.') if segment_extension_length == 3: segment_extension = '{0:s}{1:s}{2:s}'.format( first_letter, second_letter, third_letter) elif segment_extension_length == 4: segment_extension = '{0:s}x{1:s}{2:s}'.format( first_letter, second_letter, third_letter) return segment_files
[ "def", "EWFGlobPathSpec", "(", "file_system", ",", "path_spec", ")", ":", "if", "not", "path_spec", ".", "HasParent", "(", ")", ":", "raise", "errors", ".", "PathSpecError", "(", "'Unsupported path specification without parent.'", ")", "parent_path_spec", "=", "path...
Globs for path specifications according to the EWF naming schema. Args: file_system (FileSystem): file system. path_spec (PathSpec): path specification. Returns: list[PathSpec]: path specifications that match the glob. Raises: PathSpecError: if the path specification is invalid. RuntimeError: if the maximum number of supported segment files is reached.
[ "Globs", "for", "path", "specifications", "according", "to", "the", "EWF", "naming", "schema", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/ewf.py#L10-L106
train
208,386
log2timeline/dfvfs
dfvfs/helpers/fake_file_system_builder.py
FakeFileSystemBuilder._AddParentDirectories
def _AddParentDirectories(self, path): """Adds the parent directories of a path to the fake file system. Args: path (str): path of the file within the fake file system. Raises: ValueError: if a parent directory is already set and is not a directory. """ path_segments = self.file_system.SplitPath(path) for segment_index in range(len(path_segments)): parent_path = self.file_system.JoinPath(path_segments[:segment_index]) file_entry = self.file_system.GetFileEntryByPath(parent_path) if file_entry and not file_entry.IsDirectory(): raise ValueError( 'Non-directory parent file entry: {0:s} already exists.'.format( parent_path)) for segment_index in range(len(path_segments)): parent_path = self.file_system.JoinPath(path_segments[:segment_index]) if not self.file_system.FileEntryExistsByPath(parent_path): self.file_system.AddFileEntry( parent_path, file_entry_type=definitions.FILE_ENTRY_TYPE_DIRECTORY)
python
def _AddParentDirectories(self, path): """Adds the parent directories of a path to the fake file system. Args: path (str): path of the file within the fake file system. Raises: ValueError: if a parent directory is already set and is not a directory. """ path_segments = self.file_system.SplitPath(path) for segment_index in range(len(path_segments)): parent_path = self.file_system.JoinPath(path_segments[:segment_index]) file_entry = self.file_system.GetFileEntryByPath(parent_path) if file_entry and not file_entry.IsDirectory(): raise ValueError( 'Non-directory parent file entry: {0:s} already exists.'.format( parent_path)) for segment_index in range(len(path_segments)): parent_path = self.file_system.JoinPath(path_segments[:segment_index]) if not self.file_system.FileEntryExistsByPath(parent_path): self.file_system.AddFileEntry( parent_path, file_entry_type=definitions.FILE_ENTRY_TYPE_DIRECTORY)
[ "def", "_AddParentDirectories", "(", "self", ",", "path", ")", ":", "path_segments", "=", "self", ".", "file_system", ".", "SplitPath", "(", "path", ")", "for", "segment_index", "in", "range", "(", "len", "(", "path_segments", ")", ")", ":", "parent_path", ...
Adds the parent directories of a path to the fake file system. Args: path (str): path of the file within the fake file system. Raises: ValueError: if a parent directory is already set and is not a directory.
[ "Adds", "the", "parent", "directories", "of", "a", "path", "to", "the", "fake", "file", "system", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/fake_file_system_builder.py#L24-L46
train
208,387
log2timeline/dfvfs
dfvfs/helpers/fake_file_system_builder.py
FakeFileSystemBuilder.AddDirectory
def AddDirectory(self, path): """Adds a directory to the fake file system. Note that this function will create parent directories if needed. Args: path (str): path of the directory within the fake file system. Raises: ValueError: if the path is already set. """ if self.file_system.FileEntryExistsByPath(path): raise ValueError('Path: {0:s} already set.'.format(path)) self._AddParentDirectories(path) self.file_system.AddFileEntry( path, file_entry_type=definitions.FILE_ENTRY_TYPE_DIRECTORY)
python
def AddDirectory(self, path): """Adds a directory to the fake file system. Note that this function will create parent directories if needed. Args: path (str): path of the directory within the fake file system. Raises: ValueError: if the path is already set. """ if self.file_system.FileEntryExistsByPath(path): raise ValueError('Path: {0:s} already set.'.format(path)) self._AddParentDirectories(path) self.file_system.AddFileEntry( path, file_entry_type=definitions.FILE_ENTRY_TYPE_DIRECTORY)
[ "def", "AddDirectory", "(", "self", ",", "path", ")", ":", "if", "self", ".", "file_system", ".", "FileEntryExistsByPath", "(", "path", ")", ":", "raise", "ValueError", "(", "'Path: {0:s} already set.'", ".", "format", "(", "path", ")", ")", "self", ".", "...
Adds a directory to the fake file system. Note that this function will create parent directories if needed. Args: path (str): path of the directory within the fake file system. Raises: ValueError: if the path is already set.
[ "Adds", "a", "directory", "to", "the", "fake", "file", "system", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/fake_file_system_builder.py#L48-L64
train
208,388
log2timeline/dfvfs
dfvfs/helpers/fake_file_system_builder.py
FakeFileSystemBuilder.AddSymbolicLink
def AddSymbolicLink(self, path, linked_path): """Adds a symbolic link to the fake file system. Args: path (str): path of the symbolic link within the fake file system. linked_path (str): path that is linked. Raises: ValueError: if the path is already set. """ if self.file_system.FileEntryExistsByPath(path): raise ValueError('Path: {0:s} already set.'.format(path)) self._AddParentDirectories(path) self.file_system.AddFileEntry( path, file_entry_type=definitions.FILE_ENTRY_TYPE_LINK, link_data=linked_path)
python
def AddSymbolicLink(self, path, linked_path): """Adds a symbolic link to the fake file system. Args: path (str): path of the symbolic link within the fake file system. linked_path (str): path that is linked. Raises: ValueError: if the path is already set. """ if self.file_system.FileEntryExistsByPath(path): raise ValueError('Path: {0:s} already set.'.format(path)) self._AddParentDirectories(path) self.file_system.AddFileEntry( path, file_entry_type=definitions.FILE_ENTRY_TYPE_LINK, link_data=linked_path)
[ "def", "AddSymbolicLink", "(", "self", ",", "path", ",", "linked_path", ")", ":", "if", "self", ".", "file_system", ".", "FileEntryExistsByPath", "(", "path", ")", ":", "raise", "ValueError", "(", "'Path: {0:s} already set.'", ".", "format", "(", "path", ")", ...
Adds a symbolic link to the fake file system. Args: path (str): path of the symbolic link within the fake file system. linked_path (str): path that is linked. Raises: ValueError: if the path is already set.
[ "Adds", "a", "symbolic", "link", "to", "the", "fake", "file", "system", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/fake_file_system_builder.py#L103-L119
train
208,389
log2timeline/dfvfs
dfvfs/credentials/manager.py
CredentialsManager.DeregisterCredentials
def DeregisterCredentials(cls, credentials): """Deregisters a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credential object is not set for the corresponding type indicator. """ if credentials.type_indicator not in cls._credentials: raise KeyError( 'Credential object not set for type indicator: {0:s}.'.format( credentials.type_indicator)) del cls._credentials[credentials.type_indicator]
python
def DeregisterCredentials(cls, credentials): """Deregisters a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credential object is not set for the corresponding type indicator. """ if credentials.type_indicator not in cls._credentials: raise KeyError( 'Credential object not set for type indicator: {0:s}.'.format( credentials.type_indicator)) del cls._credentials[credentials.type_indicator]
[ "def", "DeregisterCredentials", "(", "cls", ",", "credentials", ")", ":", "if", "credentials", ".", "type_indicator", "not", "in", "cls", ".", "_credentials", ":", "raise", "KeyError", "(", "'Credential object not set for type indicator: {0:s}.'", ".", "format", "(", ...
Deregisters a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credential object is not set for the corresponding type indicator.
[ "Deregisters", "a", "path", "specification", "credentials", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/credentials/manager.py#L22-L37
train
208,390
log2timeline/dfvfs
dfvfs/credentials/manager.py
CredentialsManager.RegisterCredentials
def RegisterCredentials(cls, credentials): """Registers a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credentials object is already set for the corresponding type indicator. """ if credentials.type_indicator in cls._credentials: raise KeyError( 'Credentials object already set for type indicator: {0:s}.'.format( credentials.type_indicator)) cls._credentials[credentials.type_indicator] = credentials
python
def RegisterCredentials(cls, credentials): """Registers a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credentials object is already set for the corresponding type indicator. """ if credentials.type_indicator in cls._credentials: raise KeyError( 'Credentials object already set for type indicator: {0:s}.'.format( credentials.type_indicator)) cls._credentials[credentials.type_indicator] = credentials
[ "def", "RegisterCredentials", "(", "cls", ",", "credentials", ")", ":", "if", "credentials", ".", "type_indicator", "in", "cls", ".", "_credentials", ":", "raise", "KeyError", "(", "'Credentials object already set for type indicator: {0:s}.'", ".", "format", "(", "cre...
Registers a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credentials object is already set for the corresponding type indicator.
[ "Registers", "a", "path", "specification", "credentials", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/credentials/manager.py#L56-L71
train
208,391
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
_GzipDecompressorState.Read
def Read(self, file_object): """Reads the next uncompressed data from the gzip stream. Args: file_object (FileIO): file object that contains the compressed stream. Returns: bytes: next uncompressed data from the compressed stream. """ file_object.seek(self.last_read, os.SEEK_SET) read_data = file_object.read(self._MAXIMUM_READ_SIZE) self.last_read = file_object.get_offset() compressed_data = b''.join([self._compressed_data, read_data]) decompressed, extra_compressed = self._decompressor.Decompress( compressed_data) self._compressed_data = extra_compressed self.uncompressed_offset += len(decompressed) return decompressed
python
def Read(self, file_object): """Reads the next uncompressed data from the gzip stream. Args: file_object (FileIO): file object that contains the compressed stream. Returns: bytes: next uncompressed data from the compressed stream. """ file_object.seek(self.last_read, os.SEEK_SET) read_data = file_object.read(self._MAXIMUM_READ_SIZE) self.last_read = file_object.get_offset() compressed_data = b''.join([self._compressed_data, read_data]) decompressed, extra_compressed = self._decompressor.Decompress( compressed_data) self._compressed_data = extra_compressed self.uncompressed_offset += len(decompressed) return decompressed
[ "def", "Read", "(", "self", ",", "file_object", ")", ":", "file_object", ".", "seek", "(", "self", ".", "last_read", ",", "os", ".", "SEEK_SET", ")", "read_data", "=", "file_object", ".", "read", "(", "self", ".", "_MAXIMUM_READ_SIZE", ")", "self", ".", ...
Reads the next uncompressed data from the gzip stream. Args: file_object (FileIO): file object that contains the compressed stream. Returns: bytes: next uncompressed data from the compressed stream.
[ "Reads", "the", "next", "uncompressed", "data", "from", "the", "gzip", "stream", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L46-L63
train
208,392
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
GzipMember._ReadMemberHeader
def _ReadMemberHeader(self, file_object): """Reads a member header. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member header cannot be read. """ file_offset = file_object.get_offset() member_header = self._ReadStructure( file_object, file_offset, self._MEMBER_HEADER_SIZE, self._MEMBER_HEADER, 'member header') if member_header.signature != self._GZIP_SIGNATURE: raise errors.FileFormatError( 'Unsupported signature: 0x{0:04x}.'.format(member_header.signature)) if member_header.compression_method != self._COMPRESSION_METHOD_DEFLATE: raise errors.FileFormatError( 'Unsupported compression method: {0:d}.'.format( member_header.compression_method)) self.modification_time = member_header.modification_time self.operating_system = member_header.operating_system if member_header.flags & self._FLAG_FEXTRA: file_offset = file_object.get_offset() extra_field_data_size = self._ReadStructure( file_object, file_offset, self._UINT16LE_SIZE, self._UINT16LE, 'extra field data size') file_object.seek(extra_field_data_size, os.SEEK_CUR) if member_header.flags & self._FLAG_FNAME: file_offset = file_object.get_offset() string_value = self._ReadString( file_object, file_offset, self._CSTRING, 'original filename') self.original_filename = string_value.rstrip('\x00') if member_header.flags & self._FLAG_FCOMMENT: file_offset = file_object.get_offset() string_value = self._ReadString( file_object, file_offset, self._CSTRING, 'comment') self.comment = string_value.rstrip('\x00') if member_header.flags & self._FLAG_FHCRC: file_object.read(2)
python
def _ReadMemberHeader(self, file_object): """Reads a member header. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member header cannot be read. """ file_offset = file_object.get_offset() member_header = self._ReadStructure( file_object, file_offset, self._MEMBER_HEADER_SIZE, self._MEMBER_HEADER, 'member header') if member_header.signature != self._GZIP_SIGNATURE: raise errors.FileFormatError( 'Unsupported signature: 0x{0:04x}.'.format(member_header.signature)) if member_header.compression_method != self._COMPRESSION_METHOD_DEFLATE: raise errors.FileFormatError( 'Unsupported compression method: {0:d}.'.format( member_header.compression_method)) self.modification_time = member_header.modification_time self.operating_system = member_header.operating_system if member_header.flags & self._FLAG_FEXTRA: file_offset = file_object.get_offset() extra_field_data_size = self._ReadStructure( file_object, file_offset, self._UINT16LE_SIZE, self._UINT16LE, 'extra field data size') file_object.seek(extra_field_data_size, os.SEEK_CUR) if member_header.flags & self._FLAG_FNAME: file_offset = file_object.get_offset() string_value = self._ReadString( file_object, file_offset, self._CSTRING, 'original filename') self.original_filename = string_value.rstrip('\x00') if member_header.flags & self._FLAG_FCOMMENT: file_offset = file_object.get_offset() string_value = self._ReadString( file_object, file_offset, self._CSTRING, 'comment') self.comment = string_value.rstrip('\x00') if member_header.flags & self._FLAG_FHCRC: file_object.read(2)
[ "def", "_ReadMemberHeader", "(", "self", ",", "file_object", ")", ":", "file_offset", "=", "file_object", ".", "get_offset", "(", ")", "member_header", "=", "self", ".", "_ReadStructure", "(", "file_object", ",", "file_offset", ",", "self", ".", "_MEMBER_HEADER_...
Reads a member header. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member header cannot be read.
[ "Reads", "a", "member", "header", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L191-L240
train
208,393
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
GzipMember._ReadMemberFooter
def _ReadMemberFooter(self, file_object): """Reads a member footer. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member footer cannot be read. """ file_offset = file_object.get_offset() member_footer = self._ReadStructure( file_object, file_offset, self._MEMBER_FOOTER_SIZE, self._MEMBER_FOOTER, 'member footer') self.uncompressed_data_size = member_footer.uncompressed_data_size
python
def _ReadMemberFooter(self, file_object): """Reads a member footer. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member footer cannot be read. """ file_offset = file_object.get_offset() member_footer = self._ReadStructure( file_object, file_offset, self._MEMBER_FOOTER_SIZE, self._MEMBER_FOOTER, 'member footer') self.uncompressed_data_size = member_footer.uncompressed_data_size
[ "def", "_ReadMemberFooter", "(", "self", ",", "file_object", ")", ":", "file_offset", "=", "file_object", ".", "get_offset", "(", ")", "member_footer", "=", "self", ".", "_ReadStructure", "(", "file_object", ",", "file_offset", ",", "self", ".", "_MEMBER_FOOTER_...
Reads a member footer. Args: file_object (FileIO): file-like object to read from. Raises: FileFormatError: if the member footer cannot be read.
[ "Reads", "a", "member", "footer", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L242-L256
train
208,394
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
GzipMember.FlushCache
def FlushCache(self): """Empties the cache that holds cached decompressed data.""" self._cache = b'' self._cache_start_offset = None self._cache_end_offset = None self._ResetDecompressorState()
python
def FlushCache(self): """Empties the cache that holds cached decompressed data.""" self._cache = b'' self._cache_start_offset = None self._cache_end_offset = None self._ResetDecompressorState()
[ "def", "FlushCache", "(", "self", ")", ":", "self", ".", "_cache", "=", "b''", "self", ".", "_cache_start_offset", "=", "None", "self", ".", "_cache_end_offset", "=", "None", "self", ".", "_ResetDecompressorState", "(", ")" ]
Empties the cache that holds cached decompressed data.
[ "Empties", "the", "cache", "that", "holds", "cached", "decompressed", "data", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L263-L268
train
208,395
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
GzipMember.GetCacheSize
def GetCacheSize(self): """Determines the size of the uncompressed cached data. Returns: int: number of cached bytes. """ if not self._cache_start_offset or not self._cache_end_offset: return 0 return self._cache_end_offset - self._cache_start_offset
python
def GetCacheSize(self): """Determines the size of the uncompressed cached data. Returns: int: number of cached bytes. """ if not self._cache_start_offset or not self._cache_end_offset: return 0 return self._cache_end_offset - self._cache_start_offset
[ "def", "GetCacheSize", "(", "self", ")", ":", "if", "not", "self", ".", "_cache_start_offset", "or", "not", "self", ".", "_cache_end_offset", ":", "return", "0", "return", "self", ".", "_cache_end_offset", "-", "self", ".", "_cache_start_offset" ]
Determines the size of the uncompressed cached data. Returns: int: number of cached bytes.
[ "Determines", "the", "size", "of", "the", "uncompressed", "cached", "data", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L270-L278
train
208,396
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
GzipMember.ReadAtOffset
def ReadAtOffset(self, offset, size=None): """Reads a byte string from the gzip member at the specified offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: offset (int): offset within the uncompressed data in this member to read from. size (Optional[int]): maximum number of bytes to read, where None represents all remaining data, to a maximum of the uncompressed cache size. Returns: bytes: data read. Raises: IOError: if the read failed. ValueError: if a negative read size or offset is specified. """ if size is not None and size < 0: raise ValueError('Invalid size value {0!s}'.format(size)) if offset < 0: raise ValueError('Invalid offset value {0!s}'.format(offset)) if size == 0 or offset >= self.uncompressed_data_size: return b'' if self._cache_start_offset is None: self._LoadDataIntoCache(self._file_object, offset) if offset > self._cache_end_offset or offset < self._cache_start_offset: self.FlushCache() self._LoadDataIntoCache(self._file_object, offset) cache_offset = offset - self._cache_start_offset if not size: return self._cache[cache_offset:] data_end_offset = cache_offset + size if data_end_offset > self._cache_end_offset: return self._cache[cache_offset:] return self._cache[cache_offset:data_end_offset]
python
def ReadAtOffset(self, offset, size=None): """Reads a byte string from the gzip member at the specified offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: offset (int): offset within the uncompressed data in this member to read from. size (Optional[int]): maximum number of bytes to read, where None represents all remaining data, to a maximum of the uncompressed cache size. Returns: bytes: data read. Raises: IOError: if the read failed. ValueError: if a negative read size or offset is specified. """ if size is not None and size < 0: raise ValueError('Invalid size value {0!s}'.format(size)) if offset < 0: raise ValueError('Invalid offset value {0!s}'.format(offset)) if size == 0 or offset >= self.uncompressed_data_size: return b'' if self._cache_start_offset is None: self._LoadDataIntoCache(self._file_object, offset) if offset > self._cache_end_offset or offset < self._cache_start_offset: self.FlushCache() self._LoadDataIntoCache(self._file_object, offset) cache_offset = offset - self._cache_start_offset if not size: return self._cache[cache_offset:] data_end_offset = cache_offset + size if data_end_offset > self._cache_end_offset: return self._cache[cache_offset:] return self._cache[cache_offset:data_end_offset]
[ "def", "ReadAtOffset", "(", "self", ",", "offset", ",", "size", "=", "None", ")", ":", "if", "size", "is", "not", "None", "and", "size", "<", "0", ":", "raise", "ValueError", "(", "'Invalid size value {0!s}'", ".", "format", "(", "size", ")", ")", "if"...
Reads a byte string from the gzip member at the specified offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: offset (int): offset within the uncompressed data in this member to read from. size (Optional[int]): maximum number of bytes to read, where None represents all remaining data, to a maximum of the uncompressed cache size. Returns: bytes: data read. Raises: IOError: if the read failed. ValueError: if a negative read size or offset is specified.
[ "Reads", "a", "byte", "string", "from", "the", "gzip", "member", "at", "the", "specified", "offset", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L288-L333
train
208,397
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
GzipMember._LoadDataIntoCache
def _LoadDataIntoCache( self, file_object, minimum_offset, read_all_data=False): """Reads and decompresses the data in the member. This function already loads as much data as possible in the cache, up to UNCOMPRESSED_DATA_CACHE_SIZE bytes. Args: file_object (FileIO): file-like object. minimum_offset (int): offset into this member's uncompressed data at which the cache should start. read_all_data (bool): True if all the compressed data should be read from the member. """ # Decompression can only be performed from beginning to end of the stream. # So, if data before the current position of the decompressor in the stream # is required, it's necessary to throw away the current decompression # state and start again. if minimum_offset < self._decompressor_state.uncompressed_offset: self._ResetDecompressorState() while not self.IsCacheFull() or read_all_data: decompressed_data = self._decompressor_state.Read(file_object) # Note that decompressed_data will be empty if there is no data left # to read and decompress. if not decompressed_data: break decompressed_data_length = len(decompressed_data) decompressed_end_offset = self._decompressor_state.uncompressed_offset decompressed_start_offset = ( decompressed_end_offset - decompressed_data_length) data_to_add = decompressed_data added_data_start_offset = decompressed_start_offset if decompressed_start_offset < minimum_offset: data_to_add = None if decompressed_start_offset < minimum_offset < decompressed_end_offset: data_add_offset = decompressed_end_offset - minimum_offset data_to_add = decompressed_data[-data_add_offset] added_data_start_offset = decompressed_end_offset - data_add_offset if not self.IsCacheFull() and data_to_add: self._cache = b''.join([self._cache, data_to_add]) if self._cache_start_offset is None: self._cache_start_offset = added_data_start_offset if self._cache_end_offset is None: self._cache_end_offset = self._cache_start_offset + len(data_to_add) else: self._cache_end_offset += len(data_to_add) # If there's no more data in the member, the unused_data value is # populated in the decompressor. When this situation arises, we rewind # to the end of the compressed_data section. unused_data = self._decompressor_state.GetUnusedData() if unused_data: seek_offset = -len(unused_data) file_object.seek(seek_offset, os.SEEK_CUR) self._ResetDecompressorState() break
python
def _LoadDataIntoCache( self, file_object, minimum_offset, read_all_data=False): """Reads and decompresses the data in the member. This function already loads as much data as possible in the cache, up to UNCOMPRESSED_DATA_CACHE_SIZE bytes. Args: file_object (FileIO): file-like object. minimum_offset (int): offset into this member's uncompressed data at which the cache should start. read_all_data (bool): True if all the compressed data should be read from the member. """ # Decompression can only be performed from beginning to end of the stream. # So, if data before the current position of the decompressor in the stream # is required, it's necessary to throw away the current decompression # state and start again. if minimum_offset < self._decompressor_state.uncompressed_offset: self._ResetDecompressorState() while not self.IsCacheFull() or read_all_data: decompressed_data = self._decompressor_state.Read(file_object) # Note that decompressed_data will be empty if there is no data left # to read and decompress. if not decompressed_data: break decompressed_data_length = len(decompressed_data) decompressed_end_offset = self._decompressor_state.uncompressed_offset decompressed_start_offset = ( decompressed_end_offset - decompressed_data_length) data_to_add = decompressed_data added_data_start_offset = decompressed_start_offset if decompressed_start_offset < minimum_offset: data_to_add = None if decompressed_start_offset < minimum_offset < decompressed_end_offset: data_add_offset = decompressed_end_offset - minimum_offset data_to_add = decompressed_data[-data_add_offset] added_data_start_offset = decompressed_end_offset - data_add_offset if not self.IsCacheFull() and data_to_add: self._cache = b''.join([self._cache, data_to_add]) if self._cache_start_offset is None: self._cache_start_offset = added_data_start_offset if self._cache_end_offset is None: self._cache_end_offset = self._cache_start_offset + len(data_to_add) else: self._cache_end_offset += len(data_to_add) # If there's no more data in the member, the unused_data value is # populated in the decompressor. When this situation arises, we rewind # to the end of the compressed_data section. unused_data = self._decompressor_state.GetUnusedData() if unused_data: seek_offset = -len(unused_data) file_object.seek(seek_offset, os.SEEK_CUR) self._ResetDecompressorState() break
[ "def", "_LoadDataIntoCache", "(", "self", ",", "file_object", ",", "minimum_offset", ",", "read_all_data", "=", "False", ")", ":", "# Decompression can only be performed from beginning to end of the stream.", "# So, if data before the current position of the decompressor in the stream"...
Reads and decompresses the data in the member. This function already loads as much data as possible in the cache, up to UNCOMPRESSED_DATA_CACHE_SIZE bytes. Args: file_object (FileIO): file-like object. minimum_offset (int): offset into this member's uncompressed data at which the cache should start. read_all_data (bool): True if all the compressed data should be read from the member.
[ "Reads", "and", "decompresses", "the", "data", "in", "the", "member", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L335-L396
train
208,398
log2timeline/dfvfs
examples/list_file_entries.py
FileEntryLister._ListFileEntry
def _ListFileEntry( self, file_system, file_entry, parent_full_path, output_writer): """Lists a file entry. Args: file_system (dfvfs.FileSystem): file system that contains the file entry. file_entry (dfvfs.FileEntry): file entry to list. parent_full_path (str): full path of the parent file entry. output_writer (StdoutWriter): output writer. """ # Since every file system implementation can have their own path # segment separator we are using JoinPath to be platform and file system # type independent. full_path = file_system.JoinPath([parent_full_path, file_entry.name]) if not self._list_only_files or file_entry.IsFile(): output_writer.WriteFileEntry(full_path) for sub_file_entry in file_entry.sub_file_entries: self._ListFileEntry(file_system, sub_file_entry, full_path, output_writer)
python
def _ListFileEntry( self, file_system, file_entry, parent_full_path, output_writer): """Lists a file entry. Args: file_system (dfvfs.FileSystem): file system that contains the file entry. file_entry (dfvfs.FileEntry): file entry to list. parent_full_path (str): full path of the parent file entry. output_writer (StdoutWriter): output writer. """ # Since every file system implementation can have their own path # segment separator we are using JoinPath to be platform and file system # type independent. full_path = file_system.JoinPath([parent_full_path, file_entry.name]) if not self._list_only_files or file_entry.IsFile(): output_writer.WriteFileEntry(full_path) for sub_file_entry in file_entry.sub_file_entries: self._ListFileEntry(file_system, sub_file_entry, full_path, output_writer)
[ "def", "_ListFileEntry", "(", "self", ",", "file_system", ",", "file_entry", ",", "parent_full_path", ",", "output_writer", ")", ":", "# Since every file system implementation can have their own path", "# segment separator we are using JoinPath to be platform and file system", "# typ...
Lists a file entry. Args: file_system (dfvfs.FileSystem): file system that contains the file entry. file_entry (dfvfs.FileEntry): file entry to list. parent_full_path (str): full path of the parent file entry. output_writer (StdoutWriter): output writer.
[ "Lists", "a", "file", "entry", "." ]
2b3ccd115f9901d89f383397d4a1376a873c83c4
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/list_file_entries.py#L40-L58
train
208,399