def get_file_info(path): # open the file the same way CPython does in posixmodule.c desired_access = api.FILE_READ_ATTRIBUTES share_mode = 0 security_attributes = None creation_disposition = api.OPEN_EXISTING flags_and_attributes = ( api.FILE_ATTRIBUTE_NORMAL | api.FILE_FLAG_BACKUP_SEMANTICS | api.FILE_FLAG_OPEN_REPARSE_POINT ) template_file = None handle = api.CreateFile( path, desired_access, share_mode, security_attributes, creation_disposition, flags_and_attributes, template_file, ) if handle == api.INVALID_HANDLE_VALUE: raise WindowsError() info = api.BY_HANDLE_FILE_INFORMATION() res = api.GetFileInformationByHandle(handle, info) handle_nonzero_success(res) handle_nonzero_success(api.CloseHandle(handle)) return info
def CryptUnprotectData(data, optional_entropy=None, prompt_struct=None, flags=0): """ Returns a tuple of (description, data) where description is the the description that was passed to the CryptProtectData call and data is the decrypted result. """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy) if optional_entropy else None data_out = DATA_BLOB() ptr_description = wintypes.LPWSTR() res = _CryptUnprotectData( data_in, ctypes.byref(ptr_description), entropy, None, # reserved prompt_struct, flags | CRYPTPROTECT_UI_FORBIDDEN, data_out, ) handle_nonzero_success(res) description = ptr_description.value if ptr_description.value is not None: ctypes.windll.kernel32.LocalFree(ptr_description) res = data_out.get_data() data_out.free() return description, res
def readlink(link): """ readlink(link) -> target Return a string representing the path to which the symbolic link points. """ handle = api.CreateFile( link, 0, 0, None, api.OPEN_EXISTING, api.FILE_FLAG_OPEN_REPARSE_POINT | api.FILE_FLAG_BACKUP_SEMANTICS, None, ) if handle == api.INVALID_HANDLE_VALUE: raise WindowsError() res = reparse.DeviceIoControl(handle, api.FSCTL_GET_REPARSE_POINT, None, 10240) bytes = create_string_buffer(res) p_rdb = cast(bytes, POINTER(api.REPARSE_DATA_BUFFER)) rdb = p_rdb.contents if not rdb.tag == api.IO_REPARSE_TAG_SYMLINK: raise RuntimeError("Expected IO_REPARSE_TAG_SYMLINK, but got %d" % rdb.tag) handle_nonzero_success(api.CloseHandle(handle)) return rdb.get_substitute_name()
def OpenProcessToken(proc_handle, access): result = ctypes.wintypes.HANDLE() proc_handle = ctypes.wintypes.HANDLE(proc_handle) handle_nonzero_success( ctypes.windll.advapi32.OpenProcessToken(proc_handle, access, ctypes.byref(result))) return result
def get_symlink_target(link): """ get_symlink_target(link) -> target Return a string representing the path to which the symbolic link points. Similar to jaraco.windows.filesystem.readlink(link) except that opened file handle is closed properly, to prevent leak """ import jaraco.windows.api.filesystem as api import jaraco.windows.error as e from ctypes import (POINTER, cast, create_string_buffer) handle = api.CreateFile( link, 0, 0, None, api.OPEN_EXISTING, api.FILE_FLAG_OPEN_REPARSE_POINT|api.FILE_FLAG_BACKUP_SEMANTICS, None, ) if handle == api.INVALID_HANDLE_VALUE: raise WindowsError() res = api.DeviceIoControl(handle, api.FSCTL_GET_REPARSE_POINT, None, 10240) bytes = create_string_buffer(res) p_rdb = cast(bytes, POINTER(api.REPARSE_DATA_BUFFER)) rdb = p_rdb.contents e.handle_nonzero_success(api.CloseHandle(handle)) if not rdb.tag == api.IO_REPARSE_TAG_SYMLINK: raise RuntimeError("Expected IO_REPARSE_TAG_SYMLINK, but got %d" % rdb.tag) return rdb.get_print_name()
def get_symlink_target(link): """ get_symlink_target(link) -> target Return a string representing the path to which the symbolic link points. Similar to jaraco.windows.filesystem.readlink(link) except that opened file handle is closed properly, to prevent leak """ import jaraco.windows.api.filesystem as api import jaraco.windows.error as e from ctypes import (POINTER, cast, create_string_buffer) handle = api.CreateFile( link, 0, 0, None, api.OPEN_EXISTING, api.FILE_FLAG_OPEN_REPARSE_POINT | api.FILE_FLAG_BACKUP_SEMANTICS, None, ) if handle == api.INVALID_HANDLE_VALUE: raise WindowsError() res = api.DeviceIoControl(handle, api.FSCTL_GET_REPARSE_POINT, None, 10240) bytes = create_string_buffer(res) p_rdb = cast(bytes, POINTER(api.REPARSE_DATA_BUFFER)) rdb = p_rdb.contents e.handle_nonzero_success(api.CloseHandle(handle)) if not rdb.tag == api.IO_REPARSE_TAG_SYMLINK: raise RuntimeError("Expected IO_REPARSE_TAG_SYMLINK, but got %d" % rdb.tag) return rdb.get_print_name()
def CryptProtectData( data, description=None, optional_entropy=None, prompt_struct=None, flags=0, ): """ Encrypt data """ data_in = DATA_BLOB(data) entropy = DATA_BLOB(optional_entropy) if optional_entropy else None data_out = DATA_BLOB() res = _CryptProtectData( data_in, description, entropy, None, # reserved prompt_struct, flags, data_out, ) handle_nonzero_success(res) res = data_out.get_data() data_out.free() return res
def get_file_info(path): # open the file the same way CPython does in posixmodule.c desired_access = api.FILE_READ_ATTRIBUTES share_mode = 0 security_attributes = None creation_disposition = api.OPEN_EXISTING flags_and_attributes = (api.FILE_ATTRIBUTE_NORMAL | api.FILE_FLAG_BACKUP_SEMANTICS | api.FILE_FLAG_OPEN_REPARSE_POINT) template_file = None handle = api.CreateFile( path, desired_access, share_mode, security_attributes, creation_disposition, flags_and_attributes, template_file, ) if handle == api.INVALID_HANDLE_VALUE: raise WindowsError() info = api.BY_HANDLE_FILE_INFORMATION() res = api.GetFileInformationByHandle(handle, info) handle_nonzero_success(res) handle_nonzero_success(api.CloseHandle(handle)) return info
def set(value): result = system.SystemParametersInfo( system.SPI_SETACTIVEWINDOWTRACKING, 0, ctypes.cast(value, ctypes.c_void_p), 0, ) handle_nonzero_success(result)
def set_delay(milliseconds): result = system.SystemParametersInfo( system.SPI_SETACTIVEWNDTRKTIMEOUT, 0, ctypes.cast(milliseconds, ctypes.c_void_p), 0, ) handle_nonzero_success(result)
def symlink(target, link, target_is_directory = False): """ An implementation of os.symlink for Windows (Vista and greater) """ target_is_directory = (target_is_directory or _is_target_a_directory(link, target)) # normalize the target (MS symlinks don't respect forward slashes) target = os.path.normpath(target) handle_nonzero_success(api.CreateSymbolicLink(link, target, target_is_directory))
def get(): value = ctypes.wintypes.BOOL() result = system.SystemParametersInfo( system.SPI_GETACTIVEWINDOWTRACKING, 0, ctypes.byref(value), 0, ) handle_nonzero_success(result) return bool(value)
def get_delay(): value = ctypes.wintypes.DWORD() result = system.SystemParametersInfo( system.SPI_GETACTIVEWNDTRKTIMEOUT, 0, ctypes.byref(value), 0, ) handle_nonzero_success(result) return int(value.value)
def no_sleep(): """ Context that prevents the computer from going to sleep. """ mode = power.ES.continuous | power.ES.system_required handle_nonzero_success(power.SetThreadExecutionState(mode)) try: yield finally: handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous))
def OpenClipboard(owner=None): """ Open the clipboard. owner [in] Handle to the window to be associated with the open clipboard. If this parameter is None, the open clipboard is associated with the current task. """ handle_nonzero_success(windll.user32.OpenClipboard(owner))
def symlink(target, link, target_is_directory=False): """ An implementation of os.symlink for Windows (Vista and greater) """ target_is_directory = (target_is_directory or _is_target_a_directory(link, target)) # normalize the target (MS symlinks don't respect forward slashes) target = os.path.normpath(target) handle_nonzero_success( api.CreateSymbolicLink(link, target, target_is_directory))
def no_sleep(): """ Context that prevents the computer from going to sleep. """ mode = power.ES.continuous | power.ES.system_required handle_nonzero_success(power.SetThreadExecutionState(mode)) try: yield finally: handle_nonzero_success( power.SetThreadExecutionState(power.ES.continuous))
def GetTokenInformation(token, information_class): """ Given a token, get the token information for it. """ data_size = ctypes.wintypes.DWORD() ctypes.windll.advapi32.GetTokenInformation(token, information_class.num, 0, 0, ctypes.byref(data_size)) data = ctypes.create_string_buffer(data_size.value) handle_nonzero_success(ctypes.windll.advapi32.GetTokenInformation(token, information_class.num, ctypes.byref(data), ctypes.sizeof(data), ctypes.byref(data_size))) return ctypes.cast(data, ctypes.POINTER(security.TOKEN_USER)).contents
def GetTokenInformation(token, information_class): """ Given a token, get the token information for it. """ data_size = ctypes.wintypes.DWORD() ctypes.windll.advapi32.GetTokenInformation(token, information_class.num, 0, 0, ctypes.byref(data_size)) data = ctypes.create_string_buffer(data_size.value) handle_nonzero_success( ctypes.windll.advapi32.GetTokenInformation(token, information_class.num, ctypes.byref(data), ctypes.sizeof(data), ctypes.byref(data_size))) return ctypes.cast(data, ctypes.POINTER(security.TOKEN_USER)).contents
def SetFileAttributes(filepath, *attrs): """ Set file attributes. e.g.: SetFileAttributes('C:\\foo', 'hidden') Each attr must be either a numeric value, a constant defined in jaraco.windows.filesystem.api, or one of the nice names defined in this function. """ nice_names = collections.defaultdict( lambda key: key, hidden = 'FILE_ATTRIBUTE_HIDDEN', read_only = 'FILE_ATTRIBUTE_READONLY', ) flags = (getattr(api, nice_names[attr], attr) for attr in attrs) flags = functools.reduce(operator.or_, flags) handle_nonzero_success(api.SetFileAttributes(filepath, flags))
def SetFileAttributes(filepath, *attrs): """ Set file attributes. e.g.: SetFileAttributes('C:\\foo', 'hidden') Each attr must be either a numeric value, a constant defined in jaraco.windows.filesystem.api, or one of the nice names defined in this function. """ nice_names = collections.defaultdict( lambda key: key, hidden='FILE_ATTRIBUTE_HIDDEN', read_only='FILE_ATTRIBUTE_READONLY', ) flags = (getattr(api, nice_names[attr], attr) for attr in attrs) flags = functools.reduce(operator.or_, flags) handle_nonzero_success(api.SetFileAttributes(filepath, flags))
def notify(class_): """ Notify other windows that the environment has changed (following http://support.microsoft.com/kb/104011). """ # TODO: Implement Microsoft UIPI (User Interface Privilege Isolation) to # elevate privilege to system level so the system gets this notification # for now, this must be run as admin to work as expected return_val = ctypes.wintypes.DWORD() res = message.SendMessageTimeout( message.HWND_BROADCAST, message.WM_SETTINGCHANGE, 0, # wparam must be null 'Environment', message.SMTO_ABORTIFHUNG, 5000, # timeout in ms return_val, ) error.handle_nonzero_success(res)
def get_final_path(path): """ For a given path, determine the ultimate location of that path. Useful for resolving symlink targets. This functions wraps the GetFinalPathNameByHandle from the Windows SDK. Note, this function fails if a handle cannot be obtained (such as for C:\Pagefile.sys on a stock windows system). Consider using trace_symlink_target instead. """ desired_access = api.NULL share_mode = ( api.FILE_SHARE_READ | api.FILE_SHARE_WRITE | api.FILE_SHARE_DELETE ) security_attributes = api.LPSECURITY_ATTRIBUTES() # NULL pointer hFile = api.CreateFile( path, desired_access, share_mode, security_attributes, api.OPEN_EXISTING, api.FILE_FLAG_BACKUP_SEMANTICS, api.NULL, ) if hFile == api.INVALID_HANDLE_VALUE: raise WindowsError() buf_size = api.GetFinalPathNameByHandle( hFile, LPWSTR(), 0, api.VOLUME_NAME_DOS) handle_nonzero_success(buf_size) buf = create_unicode_buffer(buf_size) result_length = api.GetFinalPathNameByHandle( hFile, buf, len(buf), api.VOLUME_NAME_DOS) assert result_length < len(buf) handle_nonzero_success(result_length) handle_nonzero_success(api.CloseHandle(hFile)) return buf[:result_length]
def get_final_path(path): r""" For a given path, determine the ultimate location of that path. Useful for resolving symlink targets. This functions wraps the GetFinalPathNameByHandle from the Windows SDK. Note, this function fails if a handle cannot be obtained (such as for C:\Pagefile.sys on a stock windows system). Consider using trace_symlink_target instead. """ desired_access = api.NULL share_mode = (api.FILE_SHARE_READ | api.FILE_SHARE_WRITE | api.FILE_SHARE_DELETE) security_attributes = api.LPSECURITY_ATTRIBUTES() # NULL pointer hFile = api.CreateFile( path, desired_access, share_mode, security_attributes, api.OPEN_EXISTING, api.FILE_FLAG_BACKUP_SEMANTICS, api.NULL, ) if hFile == api.INVALID_HANDLE_VALUE: raise WindowsError() buf_size = api.GetFinalPathNameByHandle(hFile, LPWSTR(), 0, api.VOLUME_NAME_DOS) handle_nonzero_success(buf_size) buf = create_unicode_buffer(buf_size) result_length = api.GetFinalPathNameByHandle(hFile, buf, len(buf), api.VOLUME_NAME_DOS) assert result_length < len(buf) handle_nonzero_success(result_length) handle_nonzero_success(api.CloseHandle(hFile)) return buf[:result_length]
def EmptyClipboard(): handle_nonzero_success(windll.user32.EmptyClipboard())
def CloseClipboard(): handle_nonzero_success(windll.user32.CloseClipboard())
def GetEnvironmentVariable(name): max_size = 2**15-1 buffer = ctypes.create_unicode_buffer(max_size) error.handle_nonzero_success(environ.GetEnvironmentVariable(name, buffer, max_size)) return buffer.value
def GetBinaryType(filepath): res = api.DWORD() handle_nonzero_success(api._GetBinaryType(filepath, res)) return res
def link(target, link): """ Establishes a hard link between an existing file and a new file. """ handle_nonzero_success(api.CreateHardLink(link, target, None))
def ClearEnvironmentVariable(name): error.handle_nonzero_success(environ.SetEnvironmentVariable(name, None))
def OpenProcessToken(proc_handle, access): result = ctypes.wintypes.HANDLE() proc_handle = ctypes.wintypes.HANDLE(proc_handle) handle_nonzero_success(ctypes.windll.advapi32.OpenProcessToken( proc_handle, access, ctypes.byref(result))) return result
def GetSystemPowerStatus(): stat = power.SYSTEM_POWER_STATUS() handle_nonzero_success(GetSystemPowerStatus(stat)) return stat
def GetEnvironmentVariable(name): max_size = 2**15 - 1 buffer = ctypes.create_unicode_buffer(max_size) error.handle_nonzero_success( environ.GetEnvironmentVariable(name, buffer, max_size)) return buffer.value
def SetEnvironmentVariable(name, value): error.handle_nonzero_success(environ.SetEnvironmentVariable(name, value))
'CF_TEXT', 'GetClipboardData', 'CloseClipboard', 'SetClipboardData', 'OpenClipboard', ) def OpenClipboard(owner=None): """ Open the clipboard. owner [in] Handle to the window to be associated with the open clipboard. If this parameter is None, the open clipboard is associated with the current task. """ handle_nonzero_success(windll.user32.OpenClipboard(owner)) CloseClipboard = lambda: handle_nonzero_success(windll.user32.CloseClipboard()) data_handlers = dict() def handles(*formats): def register(func): for format in formats: data_handlers[format] = func return func return register def nts(s): """ Null Terminated String Get the portion of s up to a null character. """ result, null, rest = s.partition('\x00')
) def OpenClipboard(owner=None): """ Open the clipboard. owner [in] Handle to the window to be associated with the open clipboard. If this parameter is None, the open clipboard is associated with the current task. """ handle_nonzero_success(windll.user32.OpenClipboard(owner)) CloseClipboard = lambda: handle_nonzero_success(windll.user32.CloseClipboard()) data_handlers = dict() def handles(*formats): def register(func): for format in formats: data_handlers[format] = func return func return register def nts(s): """