CBFS Direct 2022 Python Edition
Version 22.0 [Build 8426]

CBDirect Class

Properties   Methods   Events   Config Settings   Errors  

The CBDirect class provides applications with low-level, direct access to disks and memory in Windows.

Syntax

class cbfsdirect.CBDirect

Remarks

The CBDirect class is used to gain low-level, direct access to disks and memory in Windows. The class allows bypassing certain Windows access restrictions, even under limited user accounts.

Getting Started

All of the CBDirect class's methods are independent, and can be called immediately after creating an instance of the class.

Here's how to get up and running:

  1. If the system driver hasn't been installed yet, call the install method to do so. This only needs to be done once.
    • In production, the system driver can be installed (or updated) ahead-of-time by the application's installation script using the Installer DLL. Please refer to the Driver Installation topic for more information.
  2. Call the class's methods as needed.
  3. To uninstall the system driver, call the uninstall method. This should not be done as part of the driver upgrade process.
    • In production, the system driver can be uninstalled by the application's uninstallation script using the Installer DLL. Please refer to the Driver Installation topic for more information.

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

tagStores application-defined data specific to this instance of the class.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

configSets or retrieves a configuration setting.
create_fileCreates or opens a file or directory by passing the request directly to the filesystem.
create_file_as_streamCreates or opens a file as a stream by passing the request directly to the filesystem.
delete_fileDeletes a file by passing the request directly to the filesystem.
get_driver_statusRetrieves the status of the class's system driver.
get_driver_versionRetrieves the version of the class's system driver.
get_sector_countReturns the number of sectors on the specified disk device.
get_sector_sizeReturns the sector size used by the specified disk device.
initializeInitializes the class.
installInstalls (or upgrades) the class's system driver.
open_memoryProvides raw, read-only access to the system's physical memory.
open_memory_as_streamProvides raw, read-only access to the system's physical memory as a stream.
open_volumeOpens a volume.
open_volume_as_streamOpens a volume as a stream.
read_sectorsReads data from sectors of a disk.
shutdown_systemShuts down or reboots the operating system.
uninstallUninstalls the class's system driver.
write_sectorsWrites data to sectors on a disk.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_errorFires if an unhandled error occurs during an event.

Config Settings


The following is a list of config settings for the class with short descriptions. Click on the links for further details.

BuildInfoInformation about the product's build.
LicenseInfoInformation about the current license.

tag Property

Stores application-defined data specific to this instance of the class.

Syntax

def get_tag() -> int: ...
def set_tag(value: int) -> None: ...

tag = property(get_tag, set_tag)

Default Value

0

Remarks

This property can be used to store data specific to a particular instance of the class.

config Method

Sets or retrieves a configuration setting.

Syntax

def config(configuration_string: str) -> str: ...

Remarks

config is a generic method available in every class. It is used to set and retrieve configuration settings for the class.

These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the config method.

To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).

To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.

create_file Method

Creates or opens a file or directory by passing the request directly to the filesystem.

Syntax

def create_file(file_name: str, desired_access: int, creation_disposition: int, flags_and_attributes: int) -> int: ...

Remarks

This method should be used instead of the Windows API's CreateFile function to create or open the file or directory specified by FileName when some other process has it open exclusively, or when the application doesn't have sufficient security rights/permissions to access it in a "standard" way.

If the file or directory is created or opened successfully, this method returns a file handle for it; otherwise, it returns INVALID_HANDLE_VALUE. The returned handle, if valid, must be closed using the Windows API's CloseHandle function when the application is finished with it.

The returned handle can be used with the Windows API's ReadFile and WriteFile functions.

The FileName, DesiredAccess, CreationDisposition, and FlagsAndAttributes parameters correspond to the lpFileName, dwDesiredAccess, dwCreationDisposition, and dwFlagsAndAttributes parameters of the Windows API's CreateFile function (respectively). Please refer to Microsoft's documentation for more information on how to set these parameters appropriately.

create_file_as_stream Method

Creates or opens a file as a stream by passing the request directly to the filesystem.

Syntax

def create_file_as_stream(file_name: str, desired_access: int, creation_disposition: int, flags_and_attributes: int) -> CBFSDirectStream: ...

Remarks

This method should be used instead of the Windows API's CreateFile function to create or open the file specified by FileName when some other process has it open exclusively, or when the application doesn't have sufficient security rights/permissions to access it in a "standard" way.

If the file is created or opened successfully, this method returns a stream object that provides access to its data; otherwise, it returns None.

The FileName, DesiredAccess, CreationDisposition, and FlagsAndAttributes parameters correspond to the lpFileName, dwDesiredAccess, dwCreationDisposition, and dwFlagsAndAttributes parameters of the Windows API's CreateFile function (respectively). Please refer to Microsoft's documentation for more information on how to set these parameters appropriately.

delete_file Method

Deletes a file by passing the request directly to the filesystem.

Syntax

def delete_file(file_name: str, close_open_handles: bool) -> None: ...

Remarks

This method should be used instead of the Windows API's DeleteFile function to delete the file specified by FileName when some other process has it open exclusively, or when the application doesn't have sufficient security rights/permissions to access it in a "standard" way.

If CloseOpenHandles is True, this method closes and invalidates all opened handles to the file before deleting it.

get_driver_status Method

Retrieves the status of the class's system driver.

Syntax

def get_driver_status(product_guid: str) -> int: ...

Remarks

This method retrieves the status of the class's system driver. This status can then be used to verify whether it has been properly installed and is ready for use.

The value returned by the method corresponds to the dwCurrentState field of the SERVICE_STATUS structure from the Windows API. It will be one of the following:

MODULE_STATUS_NOT_PRESENT0x00000000The specified module is not present on the system.

MODULE_STATUS_STOPPED0x00000001The specified module is in the Stopped state.

MODULE_STATUS_RUNNING0x00000004The specified module is loaded and running.

ProductGUID is used to distinguish between driver installations performed by different applications. Such information is necessary to guard against unexpected situations such as, e.g., the driver being uninstalled by one application despite other applications still needing it.

Therefore, to ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

Note: This method cannot be called within events.

get_driver_version Method

Retrieves the version of the class's system driver.

Syntax

def get_driver_version(product_guid: str) -> int: ...

Remarks

This method retrieves the version of the class's system driver. The value is returned as a 64-bit integer composed of four 16-bit words that each correspond to a piece of the overall module version. For example, a version of 2.32.6.28 would cause the value 0x000200200006001C to be returned.

If the class's system driver is not installed, this method returns 0.

ProductGUID is used to distinguish between driver installations performed by different applications. Such information is necessary to guard against unexpected situations such as, e.g., the driver being uninstalled by one application despite other applications still needing it.

Therefore, to ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

Note: This method cannot be called within events.

get_sector_count Method

Returns the number of sectors on the specified disk device.

Syntax

def get_sector_count(volume_handle: int) -> int: ...

Remarks

This method returns the number of sectors on the disk device identified by VolumeHandle. The value passed for VolumeHandle must be a volume handle obtained from the open_volume method; refer to its documentation for more information.

get_sector_size Method

Returns the sector size used by the specified disk device.

Syntax

def get_sector_size(volume_handle: int) -> int: ...

Remarks

This method returns the sector size, in bytes, that is used by the disk device identified by VolumeHandle. The value passed for VolumeHandle must be a volume handle obtained from the open_volume method; refer to its documentation for more information.

initialize Method

Initializes the class.

Syntax

def initialize(product_guid: str) -> None: ...

Remarks

This method initializes the class and must be called each time the application starts before attempting to call any of the class's other methods with the exception of installation-related methods.

ProductGUID is used to distinguish between driver installations performed by different applications. Such information is necessary to guard against unexpected situations such as, e.g., the driver being uninstalled by one application despite other applications still needing it.

The GUID must be specified in so-called "Registry Format" (e.g., "{1FAD0EF2-9A03-4B87-B4BC-645B7035ED90}") with curly braces included.

To ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

If the required driver was not installed using the install method with the same value of ProductGUID, initialize will return a ERROR_FILE_NOT_FOUND error (Win32 error code 2).

install Method

Installs (or upgrades) the class's system driver.

Syntax

def install(cab_file_name: str, product_guid: str, path_to_install: str, flags: int) -> bool: ...

Remarks

This method is used to install or upgrade the class's system driver. If the system must be rebooted to complete the installation process, this method returns True; otherwise, it returns False.

Important: To upgrade the product's modules, use only the install method. Previously installed versions of the modules should not be uninstalled first. Calling the install method will upgrade the previously installed version.

Please refer to the Driver Installation topic for more information.

CabFileName must be the path of the .cab file containing the class's system driver. Important: This .cab file must remain on the target system (or be available in some other way) after installation, as it is required for uninstalling the driver from the system.

ProductGUID is used to distinguish between driver installations performed by different applications. Such information is necessary to guard against unexpected situations such as, e.g., the driver being uninstalled by one application despite other applications still needing it.

Therefore, to ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

PathToInstall controls where the driver is installed. Pass empty string (highly recommended) to automatically install the driver to the appropriate Windows system directory.

Flags specifies various installation options, and should contain zero or more of the following flags, OR'd together:

INSTALL_REMOVE_OLD_VERSIONS0x00000001Uninstall drivers and helper DLLs from previous class versions (e.g., 2017).

INSTALL_KEEP_START_TYPE0x00000002Keep the driver's current start type setting in the registry.

If this flag is not set (default), the installation logic will reset the driver's start type setting in the Windows registry to the default value. Setting this flag causes the installation logic to preserve the current value, which may be necessary if the user (or the application itself) set it previously.

INSTALL_OVERWRITE_SAME_VERSION0x00000004Install files when their version is the same as the version of already installed files.

If this flag is not set (default), the installation logic will overwrite the existing file only if the version number of the file being installed is larger than the version of the file being overwritten. Setting this flag causes the installation logic to overwrite the file even when it has the same version.

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

This method requires administrative rights to execute successfully. If the user account of the process that calls this method doesn't have such rights, the call will fail with an ERROR_PRIVILEGE_NOT_HELD (0x0522) error.

Note: This method cannot be called within events.

open_memory Method

Provides raw, read-only access to the system's physical memory.

Syntax

def open_memory() -> int: ...

Remarks

This method returns a handle that provides raw, read-only access to the system's physical memory.

If the memory is opened successfully, this method returns a handle for it; otherwise, if returns INVALID_HANDLE_VALUE. The returned handle, if valid, must be closed using the Windows API's CloseHandle function when the application is finished with it.

The returned handle can be used with the Windows API's ReadFile function.

open_memory_as_stream Method

Provides raw, read-only access to the system's physical memory as a stream.

Syntax

def open_memory_as_stream() -> CBFSDirectStream: ...

Remarks

This method returns a stream object that provides raw, read-only access to the system's physical memory.

If the memory is opened successfully, this method returns a stream object that provides access to its data; otherwise, it returns None.

open_volume Method

Opens a volume.

Syntax

def open_volume(volume_name: str, desired_access: int, force_unmount: bool) -> int: ...

Remarks

This method should be used instead of the Windows API's CreateFile function to open the volume specified by VolumeName when an application needs to access it directly, bypassing the system's access control mechanisms.

If the volume is opened successfully, this method returns a volume handle for it; otherwise, if returns INVALID_HANDLE_VALUE. The returned handle, if valid, must be closed using the Windows API's CloseHandle function when the application is finished with it.

The VolumeName and DesiredAccess parameters correspond to the lpFileName and dwDesiredAccess parameters of the Windows API's CreateFile function (respectively). The value passed for VolumeName may be in WinAPI or NT-native format. Please refer to Microsoft's documentation for more information on how to set these parameters appropriately.

For the volume to be opened, it must be locked. As per MSDN, if the specified volume is a system volume or contains a page file, the [Lock] operation fails. The operation will also fail if there are open files on the drive.

When the ForceUnmount parameter is False, the class's driver returns an error when it cannot open the drive. When ForceUnmount is True, the driver will attempt to unmount a volume (which may not work as well for a system volume or a volume with a pagefile on it).

open_volume_as_stream Method

Opens a volume as a stream.

Syntax

def open_volume_as_stream(volume_name: str, desired_access: int, force_unmount: bool) -> CBFSDirectStream: ...

Remarks

This method should be used instead of the Windows API's CreateFile function to open the volume specified by VolumeName when an application needs to access it directly, bypassing the system's access control mechanisms.

If the volume is opened successfully, this method returns a stream object that provides access to its data; otherwise, it returns None.

The VolumeName and DesiredAccess parameters correspond to the lpFileName and dwDesiredAccess parameters of the Windows API's CreateFile function (respectively). The value passed for VolumeName may be in WinAPI or NT-native format. Please refer to Microsoft's documentation for more information on how to set these parameters appropriately.

For the volume to be opened, it must be locked. As per MSDN, if the specified volume is a system volume or contains a page file, the [Lock] operation fails. The operation will also fail if there are open files on the drive.

When the ForceUnmount parameter is False, the class's driver returns an error when it cannot open the drive. When ForceUnmount is True, the driver will attempt to unmount a volume (which may not work as well for a system volume or a volume with a pagefile on it).

read_sectors Method

Reads data from sectors of a disk.

Syntax

def read_sectors(volume_handle: int, starting_sector: int, sector_count: int, buffer: bytes) -> None: ...

Remarks

This method reads data from sectors of the disk identified by VolumeHandle.

The value passed for VolumeHandle must be a volume handle obtained from the open_volume method; refer to its documentation for more information.

The StartingSector parameter specifies which sector to begin reading data from.

The SectorCount parameter specifies how many sectors of data to read.

The data from the disk is read into Buffer, which must be large enough to contain all of the requested data; i.e., SectorCount * SectorSize, where SectorSize is the value returned by get_sector_size.

shutdown_system Method

Shuts down or reboots the operating system.

Syntax

def shutdown_system(shutdown_prompt: str, timeout: int, force_close_apps: bool, reboot: bool) -> bool: ...

Remarks

This method shuts down or (if Reboot is True) reboots the operating system. If the appropriate privileges cannot be obtained, or if the InitiateSystemShutdown system call returns False, then this method will return False; otherwise, it returns True. This method can be used if the installation or uninstallation function requires the system to be rebooted in order to complete.

ShutdownPrompt, if non-empty, specifies a message that the OS should display to the user for Timeout seconds. If empty string is passed for ShutdownPrompt, no message is displayed and the Timeout parameter's value is ignored.

ForceCloseApps specifies whether the OS should forcefully close all applications. Please keep in mind that forceful closing of applications with unsaved data can lead to data loss.

Reboot specifies whether the OS should reboot (True) or just shut down (False).

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

Note: This method cannot be called within events.

uninstall Method

Uninstalls the class's system driver.

Syntax

def uninstall(cab_file_name: str, product_guid: str, installed_path: str, flags: int) -> bool: ...

Remarks

This method is used to uninstall the class's system driver. If the system must be rebooted to complete the uninstallation process, this method returns True; otherwise, it returns False.

Important: To upgrade the product's modules, use only the install method. Previously installed versions of the modules should not be uninstalled first. Calling the install method will upgrade the previously installed version.

Please refer to the Driver Installation topic for more information.

The same values must be passed for the CabFileName, ProductGUID, and InstalledPath parameters as were passed when install was called; please refer to its documentation for more information.

Flags specifies which versions of the class's system driver should be uninstalled, and should be set by OR'ing together one or more of the following values:

UNINSTALL_VERSION_PREVIOUS0x00000001Uninstall modules from previous product versions.

UNINSTALL_VERSION_CURRENT0x00000002Uninstall modules from the current product version.

UNINSTALL_VERSION_ALL0x00000003Uninstall modules from all product versions.

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

This method requires administrative rights to execute successfully. If the user account of the process that calls this method doesn't have such rights, the call will fail with an ERROR_PRIVILEGE_NOT_HELD (0x0522) error.

Note: This method cannot be called within events.

write_sectors Method

Writes data to sectors on a disk.

Syntax

def write_sectors(volume_handle: int, starting_sector: int, sector_count: int, buffer: bytes) -> None: ...

Remarks

This method writes data to sectors of the disk identified by VolumeHandle.

The value passed for VolumeHandle must be a volume handle obtained from the open_volume method; refer to its documentation for more information.

The StartingSector parameter specifies which sector to begin writing data to.

The SectorCount parameter specifies the number of sectors to write data to.

The data to write to the disk must be passed in Buffer, whose size must be at least as large as the amount of data that is to be written; i.e., SectorCount * SectorSize, where SectorSize is the value returned by get_sector_size.

on_error Event

Fires if an unhandled error occurs during an event.

Syntax

class CBDirectErrorEventParams(object):
  @property
  def error_code() -> int: ...

  @property
  def description() -> str: ...

# In class CBDirect:
@property
def on_error() -> Callable[[CBDirectErrorEventParams], None]: ...
@on_error.setter
def on_error(event_hook: Callable[[CBDirectErrorEventParams], None]) -> None: ...

Remarks

This event fires if an unhandled error occurs during another event. Developers can use this information to help track down unhandled errors in an application's event handlers.

CBFSDirectStream Type

Syntax

cbfsdirect.CBFSDirectStream

Remarks

The CBFSDirectStream type is returned by some of the CBDirect class's methods. All stream types in CBFS Direct share a common API, inherited from Python's io.RawIOBase class, documented below.

Note that, for brevity, many of the members offered by io.RawIOBase are not documented here; please refer to the Python documentation for more information.

Properties

length Gets the length of the stream, in bytes.

length
readable Whether the stream supports reading.

readable()
seekable Whether the stream supports seeking.

seekable()
tell Gets the current position within the stream.

tell()
writable Whether the stream supports writing.

writeable()

Methods

close Flushes and closes the stream. Has no effect if the stream is already closed.

close()
flush Forces all data held by the stream's buffers to be written out to storage.

flush()
read Reads a specified number of bytes from the stream and returns them, advancing the current position within the stream by the number of bytes read.

read(n=-1)

Up to n bytes will be read from the stream and returned. If n is unspecified or -1, all bytes are read. Fewer than n bytes may be returned if fewer than n bytes are read.

readall Reads and returns all bytes available in the stream from the current position onwards.

readall()
readinto Reads a sequence of bytes from the stream and advances the current position within the stream by the number of bytes read.

readinto(b)

Up to len(b) bytes are read into b, and the number of bytes read is returned. The object b should be a pre-allocated, writable array of bytes, either bytearray or a writable memoryview.

seek Sets the current position within the stream based on a particular point of origin.

seek(offset, whence=SEEK_SET)

offset specifies the offset in the stream to seek to, relative to whence, which must be either SEEK_SET, SEEK_CUR, or SEEK_END (or a corresponding integer value) as described by the io.IOBase.seek documentation.

Returns the new position within the stream.

truncate Sets the length of the current stream.

truncate(size=None)

Resizes the current stream to size bytes (or to the current position if size is None).

Returns the new size of the stream.

write Writes a sequence of bytes to the stream and advances the current position within the stream by the number of bytes written.

write(b)

The bytes in b are written to the stream, and the number of bytes written in returned. The object b should be an array of bytes, either bytes, bytearray, or memoryview.

CBDirect Config Settings

The class accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the config method.

Base Config Settings

BuildInfo:   Information about the product's build.

When queried, this setting will return a string containing information about the product's build.

LicenseInfo:   Information about the current license.

When queried, this setting will return a string containing information about the license this instance of a class is using. It will return the following information:

  • Product: The product the license is for.
  • Product Key: The key the license was generated from.
  • License Source: Where the license was found (e.g. RuntimeLicense, License File).
  • License Type: The type of license installed (e.g. Royalty Free, Single Server).

CBDirect Errors

Special Use Errors

21   ERROR_NOT_READY: Reported by the methods of the class if initialize has not been called or did not succeed.
575   ERROR_APP_INIT_FAILURE: Reported by the methods of the class if initialize has not been called or did not succeed. Differs from ERROR_NOT_READY (21) in that it indicates a specific situation in the internal code.
588   ERROR_FS_DRIVER_REQUIRED: Reported if the required system module was not correctly installed for the given ProductGUID.
614   ERROR_NO_CALLBACK_ACTIVE: Reported by any method that can only be called within event handlers if it is called outside an event handler.
1292   ERROR_IMPLEMENTATION_LIMIT: Reported when the timeout value provided is less than 3 seconds.
1314   ERROR_PRIVILEGE_NOT_HELD: Reported by any method that requires elevated permissions if it is called without such permissions.

Copyright (c) 2023 Callback Technologies, Inc. - All rights reserved.
CBFS Direct 2022 Python Edition - Version 22.0 [Build 8426]