Exemplo n.º 1
0
    def getCustomLogDir(self):
        if platform == 'win32':
            key = HKEY()
            if not RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                                machine().endswith('64') and
                                r'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall' or	# Assumes that the launcher is a 32bit process
                                r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
                                0, KEY_READ, ctypes.byref(key)):
                buf = ctypes.create_unicode_buffer(MAX_PATH)
                i = 0
                while True:
                    size = DWORD(MAX_PATH)
                    if RegEnumKeyEx(key, i, buf, ctypes.byref(size), None, None, None, None):
                        break

                    subkey = HKEY()
                    if not RegOpenKeyEx(key, buf, 0, KEY_READ, ctypes.byref(subkey)):
                        valtype = DWORD()
                        valsize = DWORD((len('Frontier Developments')+1)*2)
                        valbuf = ctypes.create_unicode_buffer(valsize.value / 2)
                        if not RegQueryValueEx(subkey, 'Publisher', 0, ctypes.byref(valtype), valbuf, ctypes.byref(valsize)) and valtype.value == REG_SZ and valbuf.value == 'Frontier Developments':
                            if not RegQueryValueEx(subkey, 'InstallLocation', 0, ctypes.byref(valtype), None, ctypes.byref(valsize)) and valtype.value == REG_SZ:
                                valbuf = ctypes.create_unicode_buffer(valsize.value / 2)
                                if not RegQueryValueEx(subkey, 'InstallLocation', 0, ctypes.byref(valtype), valbuf, ctypes.byref(valsize)):
                                    return(join(valbuf.value, 'Products'))
                        RegCloseKey(subkey)
                    i += 1
                RegCloseKey(key)
        return None
Exemplo n.º 2
0
def _get_win_folder_with_ctypes(csidl_name):
    import ctypes

    csidl_const = {
        "CSIDL_APPDATA": 26,
        "CSIDL_COMMON_APPDATA": 35,
        "CSIDL_LOCAL_APPDATA": 28,
    }[csidl_name]

    buf = ctypes.create_unicode_buffer(1024)
    ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)

    # Downgrade to short path name if have highbit chars. See
    # <http://bugs.activestate.com/show_bug.cgi?id=85099>.
    has_high_char = False
    for c in buf:
        if ord(c) > 255:
            has_high_char = True
            break
    if has_high_char:
        buf2 = ctypes.create_unicode_buffer(1024)
        if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
            buf = buf2

    return buf.value
Exemplo n.º 3
0
def busca_hd_externo():
    dirs = []
    for letter in 'ABCDEFGHIJKLMNPQRSTUVWXYZ':
        letter = letter + ':\\'
        if os.path.exists(letter):
            dirs.append(letter)

    for achado in dirs:
        kernel32 = ctypes.windll.kernel32
        volume_name_buffer = ctypes.create_unicode_buffer(1024)
        file_system_name_buffer = ctypes.create_unicode_buffer(1024)
        serial_number = None
        max_component_length = None
        file_system_flags = None
                
        rc = kernel32.GetVolumeInformationW(
            ctypes.c_wchar_p(achado),
            volume_name_buffer,
            ctypes.sizeof(volume_name_buffer),
            serial_number,
            max_component_length,
            file_system_flags,
            file_system_name_buffer,
            ctypes.sizeof(file_system_name_buffer)
        )

        return_value = []
        if 'Seagate Expansion Drive Gabriel' in volume_name_buffer.value:
            return achado
def _get_win_fname():
    import ctypes

    bfr = ctypes.create_unicode_buffer(1024)
    ctypes.windll.shell32.SHGetFolderPathW(None, _CSIDL_LOCAL_APPDATA, None, 0, bfr)

    # Fix to get short path name when invalid unicode is used
    needs_fix = False
    for c in bfr:
        if ord(c) > 255:
            needs_fix = True
            break
    if needs_fix:
        fix_bfr = ctypes.create_unicode_buffer(1024)
        if ctypes.windll.kernel32.GetShortPathNameW(bfr.value, fix_bfr, 1024):
            bfr = fix_bfr

    folder = bfr.value

    try:
        extension_manager = os.environ[ENV_VAR]
    except KeyError:
        raise ValueError("Could not open extension manager from env var %s" % ENV_VAR)
    version = _guess_extension_manager_version(extension_manager)

    return os.path.join(folder, "%s_%s.ini" % (_APPNAME, version))
Exemplo n.º 5
0
def get_special_folder(name):
    """Get the location of a special folder.  name should be one of
    the following: 'AppData', 'My Music', 'My Pictures', 'My Videos',
    'My Documents', 'Desktop'.

    The path to the folder will be returned, or None if the lookup
    fails
    """
    try:
        csidl = _special_folder_CSIDLs[name]
    except KeyError:
        # FIXME - this will silently fail if the dev did a typo
        # for the path name.  e.g. My Musc
        return None

    buf = ctypes.create_unicode_buffer(260)
    buf2 = ctypes.create_unicode_buffer(1024)
    SHGetSpecialFolderPath = ctypes.windll.shell32.SHGetSpecialFolderPathW
    if SHGetSpecialFolderPath(None, buf, csidl, False):
        if GetShortPathName(buf, buf2, 1024):
            return buf2.value
        else:
            return buf.value
    else:
        return None
Exemplo n.º 6
0
	def _core_machine_id(self, request, response):
		serial = ''
		machine_name = platform.uname()[1]
		if has_windll:
			from ctypes import wintypes

			k32 = ctypes.windll.kernel32
			sys_dir = ctypes.create_unicode_buffer(260)
			if not k32.GetSystemDirectoryW(ctypes.byref(sys_dir), 260):
				return ERROR_FAILURE_WINDOWS

			vol_buf = ctypes.create_unicode_buffer(260)
			fs_buf = ctypes.create_unicode_buffer(260)
			serial_num = wintypes.DWORD(0)

			if not k32.GetVolumeInformationW(ctypes.c_wchar_p(sys_dir.value[:3]),
					vol_buf, ctypes.sizeof(vol_buf), ctypes.byref(serial_num), None,
					None, fs_buf, ctypes.sizeof(fs_buf)):
				return ERROR_FAILURE_WINDOWS
			serial_num = serial_num.value
			serial = "{0:04x}-{1:04x}".format((serial_num >> 16) & 0xFFFF, serial_num & 0xFFFF)
		else:
			serial = get_hdd_label()

		response += tlv_pack(TLV_TYPE_MACHINE_ID, "%s:%s" % (serial, machine_name))
		return ERROR_SUCCESS, response
Exemplo n.º 7
0
def foreach_child(hwnd, lparam):
    buttons = [
        "yes",
        "ok",
        "accept",
        "next",
        "install",
        "run",
        "agree",
        "enable",
        "don't send",
        "continue",
    ]

    classname = create_unicode_buffer(50)
    USER32.GetClassNameW(hwnd, classname, 50)

    # Check if the class of the child is button.
    if classname.value == "Button":
        # Get the text of the button.
        length = USER32.SendMessageW(hwnd, WM_GETTEXTLENGTH, 0, 0)
        text = create_unicode_buffer(length + 1)
        USER32.SendMessageW(hwnd, WM_GETTEXT, length + 1, text)

        # Check if the button is "positive".
        for button in buttons:
            if button in text.value.lower():
                log.info("Found button \"%s\", clicking it" % text.value)
                USER32.SetForegroundWindow(hwnd)
                KERNEL32.Sleep(1000)
                USER32.SendMessageW(hwnd, BM_CLICK, 0, 0)
Exemplo n.º 8
0
        def __init__(self):

            buf = ctypes.create_unicode_buffer(MAX_PATH)
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_LOCAL_APPDATA, 0)
            self.app_dir = join(buf.value, appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)
            
            self.hkey = HKEY()
            disposition = DWORD()
            if RegCreateKeyEx(HKEY_CURRENT_USER, r'Software\Marginal\EDMarketConnector', 0, None, 0, KEY_ALL_ACCESS, None, ctypes.byref(self.hkey), ctypes.byref(disposition)):
                raise Exception()

            if disposition.value == REG_CREATED_NEW_KEY:

                # Migrate pre-1.3.4 registry location
                oldkey = HKEY()
                if not RegOpenKeyEx(HKEY_CURRENT_USER, r'Software\EDMarketConnector', 0, KEY_ALL_ACCESS, ctypes.byref(oldkey)):
                    SHCopyKey(oldkey, None, self.hkey, 0)
                    SHDeleteKey(oldkey, '')
                    RegCloseKey(oldkey)

                # set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings
                sparklekey = HKEY()
                if not RegCreateKeyEx(self.hkey, 'WinSparkle', 0, None, 0, KEY_ALL_ACCESS, None, ctypes.byref(sparklekey), ctypes.byref(disposition)):
                    if disposition.value == REG_CREATED_NEW_KEY:
                        buf = ctypes.create_unicode_buffer('1')
                        RegSetValueEx(sparklekey, 'CheckForUpdates', 0, 1, buf, len(buf)*2)
                        buf = ctypes.create_unicode_buffer(unicode(47*60*60))
                        RegSetValueEx(sparklekey, 'UpdateInterval', 0, 1, buf, len(buf)*2)
                    RegCloseKey(sparklekey)

            if not self.get('outdir') or not isdir(self.get('outdir')):
                ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_PERSONAL, 0)
                self.set('outdir', buf.value)
Exemplo n.º 9
0
def text_in_coords(query):
    p = POINT()
    p.x = query['x']
    p.y = query['y']
    ret_value = ''
    hwnd = ctypes.windll.user32.WindowFromPoint(p)
    if hwnd:
        get_window_text = ''
        max_count = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + 5
        if max_count > 5:
            buffer = ctypes.create_unicode_buffer(max_count)
            ret = ctypes.windll.user32.GetWindowTextW(hwnd, buffer, max_count)
            if ret > 0:
                get_window_text = ctypes.wstring_at(buffer)
        
        max_count = 1024
        buffer = ctypes.create_unicode_buffer(max_count)
        result = ctypes.windll.user32.GetClassNameW(hwnd, ctypes.pointer(buffer), max_count)
        if ctypes.wstring_at(buffer) == 'ComboBox':
            ret_value = {'combobox': {'value': get_window_text,
                                      'values': get_combobox_items(hwnd)}}
        else:
            WM_GETTEXT = 0x000d
            buffer = ctypes.create_unicode_buffer(max_count)
            length = ctypes.windll.user32.SendMessageW(hwnd, WM_GETTEXT, max_count, ctypes.pointer(buffer))
            get_text = ctypes.wstring_at(buffer)
            if len(get_text) > len(get_window_text):
                ret_value = get_text
            else:
                ret_value = get_window_text

    return {'status': 'ok', 'text': ret_value}
    def reset_console(self, buf_info, add_block=True): # {{{

        # sometimes we just want to change the buffer width,
        # in which case no need to add another block
        if add_block:
            self.output_blocks += 1

        # close down old memory
        self.shm_output.close()
        self.shm_output = None

        self.shm_attributes.close()
        self.shm_attributes = None

        # new shared memory key
        mem_key = 'mk' + str(time.time())

        # reallocate memory
        self.shm_output = ConqueSoleSharedMemory(self.buffer_height * self.buffer_width * self.output_blocks, 'output', mem_key, True)
        self.shm_output.create('write')
        self.shm_output.clear()

        # backfill data
        if len(self.data[0]) < self.buffer_width:
            for i in range(0, len(self.data)):
                self.data[i] = self.data[i] + ' ' * (self.buffer_width - len(self.data[i]))
        self.shm_output.write(''.join(self.data))

        self.shm_attributes = ConqueSoleSharedMemory(self.buffer_height * self.buffer_width * self.output_blocks, 'attributes', mem_key, True, chr(buf_info.wAttributes), encoding='latin-1')
        self.shm_attributes.create('write')
        self.shm_attributes.clear()

        # backfill attributes
        if len(self.attributes[0]) < self.buffer_width:
            for i in range(0, len(self.attributes)):
                self.attributes[i] = self.attributes[i] + chr(buf_info.wAttributes) * (self.buffer_width - len(self.attributes[i]))
        self.shm_attributes.write(''.join(self.attributes))

        # notify wrapper of new output block
        self.shm_rescroll.write({'cmd': 'new_output', 'data': {'blocks': self.output_blocks, 'mem_key': mem_key}})

        # set buffer size
        size = COORD(X=self.buffer_width, Y=self.buffer_height * self.output_blocks)
        logging.debug('new buffer size: ' + str(size))
        res = ctypes.windll.kernel32.SetConsoleScreenBufferSize(self.stdout, size)

        logging.debug('buf size result')
        logging.debug(str(res))
        logging.debug(str(ctypes.GetLastError()))
        logging.debug(str(ctypes.FormatError(ctypes.GetLastError())))

        # prev set size call needs to process
        time.sleep(0.2)

        # set window size
        self.set_window_size(self.window_width, self.window_height)

        # init read buffers
        self.tc = ctypes.create_unicode_buffer(self.buffer_width)
        self.ac = ctypes.create_unicode_buffer(self.buffer_width)
Exemplo n.º 11
0
def GetVolumeInformation(rootPathName):
    volumeSerialNumber = DWORD()
    maximumComponentLength = DWORD()
    fileSystemFlags = DWORD()

    if hasattr(ctypes.windll.kernel32, "GetVolumeInformationW"):
        rootPathName = decode(rootPathName)
        volumeNameBuffer = ctypes.create_unicode_buffer(MAX_PATH_NULL)
        fileSystemNameBuffer = ctypes.create_unicode_buffer(MAX_PATH_NULL)
        GVI = ctypes.windll.kernel32.GetVolumeInformationW
    else:
        volumeNameBuffer = ctypes.create_string_buffer(MAX_PATH_NULL)
        fileSystemNameBuffer = ctypes.create_string_buffer(MAX_PATH_NULL)
        GVI = ctypes.windll.kernel32.GetVolumeInformationA
    GVI(
        rootPathName,
        volumeNameBuffer,
        MAX_PATH_NULL,
        ctypes.byref(volumeSerialNumber),
        ctypes.byref(maximumComponentLength),
        ctypes.byref(fileSystemFlags),
        fileSystemNameBuffer,
        MAX_PATH_NULL,
    )
    return (
        volumeNameBuffer.value,
        volumeSerialNumber.value,
        maximumComponentLength.value,
        fileSystemFlags.value,
        fileSystemNameBuffer.value,
    )
Exemplo n.º 12
0
 def GetUserName():
     buffer = create_unicode_buffer(32)
     size = c_uint(len(buffer))
     while not GetUserNameW(buffer, byref(size)):
         buffer = create_unicode_buffer(len(buffer) * 2)
         size.value = len(buffer)
     return buffer.value.encode('utf-16-le')[::2]
Exemplo n.º 13
0
def getCurrentJobXP(vista=True):
	# get information about current active window
	# including: window title, image name
	# for Windows XP and 32-bit environment

	# required DLLs
	user32 = ctypes.windll.LoadLibrary('user32.dll')
	kernel32 = ctypes.windll.LoadLibrary('kernel32.dll')
	psapi = ctypes.windll.LoadLibrary('psapi.dll')
	# required constants
	BUFFER_LENGTH = 1024
	SYNCHRONIZE = 0x00100000L
	PROCESS_QUERY_INFORMATION = 0x0400
	PROCESS_VM_READ = 0x0010
	# some buffers
	title = ctypes.create_unicode_buffer(BUFFER_LENGTH)
	image = ctypes.create_unicode_buffer(BUFFER_LENGTH)
	length = ctypes.c_ulong(BUFFER_LENGTH)
	plength = ctypes.pointer(length)
	# start working!
	user32.GetWindowTextW(user32.GetForegroundWindow(), title, ctypes.sizeof(title))
	pid = ctypes.c_int(0)
	ppid = ctypes.pointer(pid)
	user32.GetWindowThreadProcessId(user32.GetForegroundWindow(), ppid)
	hProcess = kernel32.OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, True, pid)
	result = 0
	result = psapi.GetModuleFileNameExW(hProcess, None, image, ctypes.sizeof(image))
	if result == 0:
		print kernel32.GetLastError()
	# return results
	return {'title': title.value, 'image': image.value}
Exemplo n.º 14
0
    def SetEditText(self, text, pos_start = None, pos_end = None):
        "Set the text of the edit control"
        self.VerifyActionable()

        # allow one or both of pos_start and pos_end to be None
        if pos_start is not None or pos_end is not None:

            # if only one has been specified - then set the other
            # to the current selection start or end
            start, end = self.SelectionIndices()
            if pos_start is None:
                pos_start = start
            if pos_end is None:
                pos_end = end

            # set the selection if either start or end has
            # been specified
            self.Select(pos_start, pos_end)
        else:
            self.Select()

        # replace the selection with
        #buffer = ctypes.c_wchar_p(six.text_type(text))
        
        if isinstance(text, six.text_type):
            if six.PY3:
                buffer = ctypes.create_unicode_buffer(text, size=len(text) + 1)
            else:
                buffer = ctypes.create_string_buffer(text.encode(locale.getpreferredencoding(), 'ignore'), size=len(text) + 1)
        else:
            if six.PY3:
                buffer = ctypes.create_unicode_buffer(text.decode(locale.getpreferredencoding()), size=len(text) + 1)
            else:
                buffer = ctypes.create_string_buffer(text, size=len(text) + 1)
        #buffer = ctypes.create_unicode_buffer(text, size=len(text) + 1)
        '''
        remote_mem = RemoteMemoryBlock(self)
        _setTextExStruct = win32structures.SETTEXTEX()
        _setTextExStruct.flags = win32defines.ST_SELECTION #| win32defines.ST_UNICODE
        _setTextExStruct.codepage = win32defines.CP_WINUNICODE
        
        remote_mem.Write(_setTextExStruct)
        
        self.SendMessage(win32defines.EM_SETTEXTEX, remote_mem, ctypes.byref(buffer))
        '''
        self.SendMessage(win32defines.EM_REPLACESEL, True, ctypes.byref(buffer))

        #win32functions.WaitGuiThreadIdle(self)
        #time.sleep(Timings.after_editsetedittext_wait)

        if isinstance(text, six.text_type):
            if six.PY3:
                self.actions.log('Set text to the edit box: ' + text)
            else:
                self.actions.log('Set text to the edit box: ' + text.encode(locale.getpreferredencoding(), 'ignore'))
        elif isinstance(text, six.binary_type):
            self.actions.log(b'Set text to the edit box: ' + text)

        # return this control so that actions can be chained.
        return self
Exemplo n.º 15
0
    def get_cdrom_drive_mount_point(self):

        mount_point = None

        buf = ctypes.create_unicode_buffer(2048)
        buf_len = kernel32.GetLogicalDriveStringsW(ctypes.sizeof(buf) / ctypes.sizeof(wintypes.WCHAR), buf)
        if not buf_len:
            raise Exception("Cannot enumerate logical devices")

        cdrom_dev = self.get_physical_path().rsplit("\\")[-1].upper()

        i = 0
        while not mount_point and i < buf_len:
            curr_drive = ctypes.wstring_at(ctypes.addressof(buf) + i * ctypes.sizeof(wintypes.WCHAR))[:-1]

            dev = ctypes.create_unicode_buffer(2048)
            ret_val = kernel32.QueryDosDeviceW(curr_drive, dev, ctypes.sizeof(dev) / ctypes.sizeof(wintypes.WCHAR))
            if not ret_val:
                raise Exception("Cannot query NT device")

            if dev.value.rsplit("\\")[-1].upper() == cdrom_dev:
                mount_point = curr_drive
            else:
                i += len(curr_drive) + 2

        return mount_point
Exemplo n.º 16
0
def QueryDosDevice(drive_letter):
    devicename = ctypes.create_unicode_buffer(drive_letter)
    ucchMax = 4096
    result = ctypes.create_unicode_buffer(u'', ucchMax)
    size = ctypes.windll.kernel32.QueryDosDeviceW(ctypes.byref(devicename), ctypes.byref(result), ucchMax)
    if size == 0:
        raise ctypes.WinError()
    return result.value
Exemplo n.º 17
0
def set_registry_value(hkey, sub_key, value, data_type, data, data_len):
    # assert isinstance(hkey, ctypes.wintypes.HKEY)
    return ERROR_SUCCESS == ctypes.windll.shlwapi.SHSetValueW(hkey,
                                                              ctypes.create_unicode_buffer(sub_key),
                                                              ctypes.create_unicode_buffer(value),
                                                              data_type,
                                                              ctypes.cast(data, ctypes.c_void_p),
                                                              data_len)
Exemplo n.º 18
0
def foreach_child(hwnd, lparam):
    # List of buttons labels to click.
    buttons = [
        "yes", "oui",
        "ok",
        "i accept",
        "next", "suivant",
        "new", "nouveau",
        "install", "installer",
        "file", "fichier",
        "run", "start", "marrer", "cuter",
        "i agree", "accepte",
        "enable", "activer", "accord", "valider",
        "don't send", "ne pas envoyer",
        "continue", "continuer",
        "personal", "personnel",
        "scan", "scanner",
        "unzip", "dezip",
        "open", "ouvrir",
        "execute", "executer",
        "launch", "lancer",
        "save", "sauvegarder",
        "download", "load", "charger",
        "end", "fin", "terminer"
    ]

    # List of buttons labels to not click.
    dontclick = [
        "don't run",
        "i do not accept"
    ]

    classname = create_unicode_buffer(50)
    USER32.GetClassNameW(hwnd, classname, 50)

    # Check if the class of the child is button.
    if "button" in classname.value.lower():
        # Get the text of the button.
        length = USER32.SendMessageW(hwnd, WM_GETTEXTLENGTH, 0, 0)
        text = create_unicode_buffer(length + 1)
        USER32.SendMessageW(hwnd, WM_GETTEXT, length + 1, text)

        # Check if the button is set as "clickable" and click it.
        textval = text.value.replace("&", "").lower()
        for button in buttons:
            if button in textval:
                for btn in dontclick:
                    if btn in textval:
                        break
                else:
                    log.info("Found button \"%s\", clicking it" % text.value)
                    USER32.SetForegroundWindow(hwnd)
                    KERNEL32.Sleep(1000)
                    USER32.SendMessageW(hwnd, BM_CLICK, 0, 0)

    # Recursively search for childs (USER32.EnumChildWindows).
    return True
Exemplo n.º 19
0
 def convert_path(path, method):
     src = ctypes.create_unicode_buffer(path)
     dst = ctypes.create_unicode_buffer(MAX_PATH)
     if method(src, dst, ctypes.sizeof(dst)) != 0:
         return dst.value
     else:
         print 'Cannot convert path %s: "%s"' % (
             path, ctypes.FormatError(ctypes.GetLastError()))
         return path
Exemplo n.º 20
0
def get_token(username, password):
    username = create_unicode_buffer(username)
    domain = create_unicode_buffer(environ['COMPUTERNAME'])
    password = create_unicode_buffer(password)
    token = Ctypes.HANDLE(0)
    LogonUserW(username, domain, password,
               Ctypes.DWORD(LOGON32_LOGON_INTERACTIVE),
               Ctypes.DWORD(LOGON32_PROVIDER_WINNT50), byref(token))
    return token.value
Exemplo n.º 21
0
def getInfo(hwnd):
    length = user32.GetWindowTextLengthW(hwnd) + 1
    buffer = ctypes.create_unicode_buffer(length)
    user32.GetWindowTextW(hwnd, buffer, length)
    b2 = ctypes.create_unicode_buffer(200)
    user32.GetClassNameW(hwnd,b2,200);
    title=buffer.value
    c=b2.value
    return title,c
Exemplo n.º 22
0
def get_final_path_name_by_handle(handle, flags):
    path = create_unicode_buffer(MAX_PATH)
    while True:
        ret = kernel32.GetFinalPathNameByHandleW(handle, path, len(path), flags)
        if not ret:
            raise windows_error()
        if ret < len(path):
            return path[:ret]
        path = create_unicode_buffer(ret)
Exemplo n.º 23
0
 def set_volume_label(self, mount_point, label):
     """:raises: `OverflowError if the label is too big"""
     if not mount_point.endswith('\\'):
         mount_point = u"{}\\".format(mount_point)
     try:
         SetVolumeLabelW(rootPathName=create_unicode_buffer(mount_point),
                         volumeName=create_unicode_buffer(label))
     except WindowsException, e:
         raise
Exemplo n.º 24
0
    def getLogDir(self):
        if platform == 'win32':
            # https://support.elitedangerous.com/kb/faq.php?id=108
            candidates = []

            # Steam and Steam libraries
            key = HKEY()
            if not RegOpenKeyEx(HKEY_CURRENT_USER, r'Software\Valve\Steam', 0, KEY_READ, ctypes.byref(key)):
                valtype = DWORD()
                valsize = DWORD()
                if not RegQueryValueEx(key, 'SteamPath', 0, ctypes.byref(valtype), None, ctypes.byref(valsize)) and valtype.value == REG_SZ:
                    buf = ctypes.create_unicode_buffer(valsize.value / 2)
                    if not RegQueryValueEx(key, 'SteamPath', 0, ctypes.byref(valtype), buf, ctypes.byref(valsize)):
                        steampath = buf.value.replace('/', '\\')	# For some reason uses POSIX seperators
                        steamlibs = [steampath]
                        try:
                            # Simple-minded Valve VDF parser
                            with open(join(steampath, 'config', 'config.vdf'), 'rU') as h:
                                for line in h:
                                    vals = line.split()
                                    if vals and vals[0].startswith('"BaseInstallFolder_'):
                                        steamlibs.append(vals[1].strip('"').replace('\\\\', '\\'))
                        except:
                            pass
                        for lib in steamlibs:
                            candidates.append(join(lib, 'steamapps', 'common', 'Elite Dangerous Horizons', 'Products'))
                            candidates.append(join(lib, 'steamapps', 'common', 'Elite Dangerous', 'Products'))
                RegCloseKey(key)

            # Next try custom installation under the Launcher
            candidates.append(self.getCustomLogDir() or '')

            # Standard non-Steam locations
            programs = ctypes.create_unicode_buffer(MAX_PATH)
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, programs, CSIDL_PROGRAM_FILESX86, 0)
            candidates.append(join(programs.value, 'Frontier', 'Products')),

            applocal = ctypes.create_unicode_buffer(MAX_PATH)
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, applocal, CSIDL_LOCAL_APPDATA, 0)
            candidates.append(join(applocal.value, 'Frontier_Developments', 'Products'))

            for game in ['elite-dangerous-64', 'FORC-FDEV-D-1']:	# Look for Horizons in all candidate places first
                for base in candidates:
                    if isdir(base):
                        for d in listdir(base):
                            if d.startswith(game) and isfile(join(base, d, 'AppConfig.xml')) and isdir(join(base, d, 'Logs')):
                                return join(base, d, 'Logs')

        elif platform == 'darwin':
            # https://support.frontier.co.uk/kb/faq.php?id=97
            suffix = join("Frontier Developments", "Elite Dangerous", "Logs")
            paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)
            if len(paths) and isdir(join(paths[0], suffix)):
                return join(paths[0], suffix)

        return None	# not found in standard places
Exemplo n.º 25
0
def foreach_child(hwnd, lparam):
    # List of buttons labels to click.
    buttons = [
        "yes",
        "ok",
        "accept",
        "next",
        "install",
        "run",
        "agree",
        "enable",
        "don't send",
        "don't save",
        "continue",
        "unzip",
        "open",
        "close the program",
        "save",
        "later",
        "finish",
        "end",
    ]

    # List of buttons labels to not click.
    dontclick = [
        "don't run",
        "do not ask again until the next update is available",
    ]

    classname = create_unicode_buffer(128)
    USER32.GetClassNameW(hwnd, classname, 128)

    # Check if the class of the child is button.
    if "button" in classname.value.lower():
        # Get the text of the button.
        length = USER32.SendMessageW(hwnd, WM_GETTEXTLENGTH, 0, 0)
        if not length:
            return True
        text = create_unicode_buffer(length + 1)
        USER32.SendMessageW(hwnd, WM_GETTEXT, length + 1, text)
        textval = text.value.replace('&','')
        # Check if the button is set as "clickable" and click it.
        for button in buttons:
            if button in textval.lower():
                dontclickb = False
                for btn in dontclick:
                    if btn in textval.lower():
                        dontclickb = True
                if not dontclickb:
                    log.info("Found button \"%s\", clicking it" % text.value)
                    USER32.SetForegroundWindow(hwnd)
                    KERNEL32.Sleep(1000)
                    USER32.SendMessageW(hwnd, BM_CLICK, 0, 0)
                    # only stop searching when we click a button
                    return False
    return True
Exemplo n.º 26
0
def get_current_username():
    """
    Name of the current username.
    """
    buffer = create_unicode_buffer(256)
    size = c_uint(len(buffer))
    while not GetUserNameW(buffer, byref(size)):
        buffer = create_unicode_buffer(len(buffer) * 2)
        size.value = len(buffer)
    return buffer.value
Exemplo n.º 27
0
        def test_buffers(self):
            buf = ctypes.create_unicode_buffer("abc")
            self.assertEqual(len(buf), 3+1)

            buf = ctypes.create_unicode_buffer("ab\xe4\xf6\xfc")
            self.assertEqual(buf[:], "ab\xe4\xf6\xfc\0")
            self.assertEqual(buf[::], "ab\xe4\xf6\xfc\0")
            self.assertEqual(buf[::-1], '\x00\xfc\xf6\xe4ba')
            self.assertEqual(buf[::2], 'a\xe4\xfc')
            self.assertEqual(buf[6:5:-1], "")
Exemplo n.º 28
0
def select_icon(iconpath=None, iconnum=0):
    if iconpath is None:
        piconpath = create_unicode_buffer(260)  # 260: https://stackoverflow.com/a/1880453/321973
    else:
        piconpath = create_unicode_buffer(iconpath, 260)
    piconnum = wintypes.INT(iconnum)
    if windll.shell32.PickIconDlg(None, byref(piconpath), len(piconpath), byref(piconnum)) == 1:
        return piconpath.value, piconnum.value
    else:
        raise NoIconPickedError
Exemplo n.º 29
0
 def GetUserName():
     buffer = create_unicode_buffer(2)
     size = c_uint(len(buffer))
     while not GetUserNameW(buffer, byref(size)):
         errcd = getLastError()
         if errcd == 234:
             # bad wine implementation up through wine 1.3.21
             return "AlternateUserName"
         buffer = create_unicode_buffer(len(buffer) * 2)
         size.value = len(buffer)
     return buffer.value.encode('utf-16-le')[::2]
Exemplo n.º 30
0
 def set(self, key, val):
     if isinstance(val, basestring):
         buf = ctypes.create_unicode_buffer(val)
         RegSetValueEx(self.hkey, key, 0, REG_SZ, buf, len(buf)*2)
     elif isinstance(val, numbers.Integral):
         RegSetValueEx(self.hkey, key, 0, REG_DWORD, ctypes.byref(DWORD(val)), 4)
     elif hasattr(val, '__iter__'):	# iterable
         stringval = u'\x00'.join([unicode(x) or u' ' for x in val] + [u''])	# null terminated non-empty strings
         buf = ctypes.create_unicode_buffer(stringval)
         RegSetValueEx(self.hkey, key, 0, REG_MULTI_SZ, buf, len(buf)*2)
     else:
         raise NotImplementedError()
Exemplo n.º 31
0
def get_text(obj_handle, num=32):
    buf = ctypes.create_unicode_buffer(num)
    user32.SendMessageW(obj_handle, MSG['WM_GETTEXT'], num, buf)
    return buf.value
Exemplo n.º 32
0
def foreach_child(hwnd, lparam):
    # List of buttons labels to click.
    buttons = [
        "yes",
        "ok",
        "accept",
        "next",
        "install",
        "run",
        "agree",
        "enable",
        "don't send",
        "don't save",
        "continue",
        "unzip",
        "open",
        "close the program",
        "save",
        "later",
        "finish",
        "end",
        "allow access",
    ]

    # List of buttons labels to not click.
    dontclick = [
        "check online for a solution", "don't run",
        "do not ask again until the next update is available", "cancel",
        "do not accept the agreement"
    ]

    classname = create_unicode_buffer(128)
    USER32.GetClassNameW(hwnd, classname, 128)

    # Check if the class of the child is button.
    if "button" in classname.value.lower(
    ) or classname.value == "NUIDialog" or classname.value == "bosa_sdm_msword":
        # Get the text of the button.
        length = USER32.SendMessageW(hwnd, WM_GETTEXTLENGTH, 0, 0)
        if not length:
            return True
        text = create_unicode_buffer(length + 1)
        USER32.SendMessageW(hwnd, WM_GETTEXT, length + 1, text)
        textval = text.value.replace('&', '')
        if "Microsoft" in textval and (classname.value == "NUIDialog" or
                                       classname.value == "bosa_sdm_msword"):
            log.info("Issuing keypress on Office dialog")
            USER32.SetForegroundWindow(hwnd)
            # enter key down/up
            USER32.keybd_event(0x0d, 0x1c, 0, 0)
            USER32.keybd_event(0x0d, 0x1c, 2, 0)
            return False

        # we don't want to bother clicking any non-visible child elements, as they
        # generally won't respond and will cause us to fixate on them for the
        # rest of the analysis, preventing progress with visible elements

        if not USER32.IsWindowVisible(hwnd):
            return True

        # Check if the button is set as "clickable" and click it.
        for button in buttons:
            if button in textval.lower():
                dontclickb = False
                for btn in dontclick:
                    if btn in textval.lower():
                        dontclickb = True
                if not dontclickb:
                    log.info("Found button \"%s\", clicking it" % text.value)
                    USER32.SetForegroundWindow(hwnd)
                    KERNEL32.Sleep(1000)
                    USER32.SendMessageW(hwnd, BM_CLICK, 0, 0)
                    # only stop searching when we click a button
                    return False
    return True
Exemplo n.º 33
0
def _decode_dl(input: bytes, *, encoding):
    cd = _iconv_open(b'WCHAR_T', bytes(encoding, 'ASCII'))
    assert isinstance(cd, int)
    if cd == ctypes.c_void_p(-1).value:
        rc = ctypes.get_errno()
        raise OSError(rc, os.strerror(rc))
    try:
        c_input = ctypes.c_char_p(input)
        output_len = len(input)
        while True:
            inbuf = ctypes.cast(c_input, ctypes.POINTER(ctypes.c_char))
            inbytesleft = ctypes.c_size_t(len(input))
            assert inbytesleft.value == len(input)  # no overflow
            outbuf = ctypes.create_unicode_buffer(output_len)
            outbytesleft = ctypes.c_size_t(output_len)  # no overflow
            assert outbytesleft.value == output_len
            rc = _iconv(cd, None, None, None, None)
            if rc == ctypes.c_size_t(-1).value:
                rc = ctypes.get_errno()
                raise OSError(rc, os.strerror(rc))
            inbufptr = ctypes.pointer(
                ctypes.cast(inbuf, ctypes.POINTER(ctypes.c_char)))
            outbufptr = ctypes.pointer(
                ctypes.cast(outbuf, ctypes.POINTER(ctypes.c_char)))
            rc = _iconv(
                cd,
                inbufptr,
                ctypes.byref(inbytesleft),
                outbufptr,
                ctypes.byref(outbytesleft),
            )
            if rc != ctypes.c_size_t(-1).value:
                rc = _iconv(
                    cd,
                    None,
                    None,
                    outbufptr,
                    ctypes.byref(outbytesleft),
                )
            if rc == ctypes.c_size_t(-1).value:
                rc = ctypes.get_errno()
                if rc == errno.E2BIG:
                    output_len *= 2
                    continue
                elif rc in {errno.EILSEQ, errno.EINVAL}:
                    begin = len(input) - inbytesleft.value
                    for end in range(begin + 1, len(input)):
                        # Assume that the encoding can be synchronized on ASCII characters.
                        # That's not necessarily true for _every_ encoding, but oh well.
                        if input[end] < 0x80:
                            break
                    else:
                        end = len(input)
                    raise UnicodeDecodeError(
                        encoding,
                        input,
                        begin,
                        end,
                        os.strerror(errno.EILSEQ),
                    )
                raise OSError(rc, os.strerror(rc))
            assert inbytesleft.value == 0, '{n} bytes left'.format(
                n=inbytesleft.value)
            output_len -= outbytesleft.value
            assert output_len % ctypes.sizeof(ctypes.c_wchar) == 0
            unicode_output_len = output_len // ctypes.sizeof(ctypes.c_wchar)
            return outbuf[:unicode_output_len]
    finally:
        rc = _iconv_close(cd)
        if rc != 0:
            rc = ctypes.get_errno()
            raise OSError(rc, os.strerror(rc))
Exemplo n.º 34
0
 def callback(handle):
     class_name = ctypes.create_unicode_buffer(len(target_class))
     user32.GetClassNameW(handle, class_name, len(target_class) + 1)
     if target_class == class_name.value:
         return True
Exemplo n.º 35
0
def environment_string(env):
    senv = ""
    for k, v in env.items():
        senv += k + "=" + v + "\0"
    senv += "\0"
    return ctypes.create_unicode_buffer(senv)
Exemplo n.º 36
0
 def enum_windows_cb(hwnd, lparam):
     if not IsWindowVisible(hwnd):
         l("skipped invisible window %#x", hwnd)
         return True
     pid = c_int()
     thread_id = GetWindowThreadProcessId(hwnd, byref(pid))
     if pid==ourpid:
         l("skipped our own window %#x", hwnd)
         return True
     #skipping IsWindowEnabled check
     length = GetWindowTextLengthW(hwnd)
     buf = create_unicode_buffer(length+1)
     if GetWindowTextW(hwnd, buf, length+1)>0:
         window_title = buf.value
     else:
         window_title = ''
     l("get_shape_rectangles() found window '%s' with pid=%i and thread id=%i", window_title, pid, thread_id)
     rect = RECT()
     if GetWindowRect(hwnd, byref(rect))==0:
         l("GetWindowRect failure")
         return True
     left, top, right, bottom = rect.left, rect.top, rect.right, rect.bottom
     if right<0 or bottom<0:
         l("skipped offscreen window at %ix%i", right, bottom)
         return True
     if hwnd==taskbar:
         l("skipped taskbar")
         return True
     #dirty way:
     if window_title=='Program Manager':
         return True
     #this should be the proper way using GetTitleBarInfo (but does not seem to work)
     #import ctypes
     #from ctypes.windll.user32 import GetTitleBarInfo        #@UnresolvedImport
     #from ctypes.wintypes import (DWORD, RECT)
     #class TITLEBARINFO(ctypes.Structure):
     #    pass
     #TITLEBARINFO._fields_ = [
     #    ('cbSize', DWORD),
     #    ('rcTitleBar', RECT),
     #    ('rgstate', DWORD * 6),
     #]
     #ti = TITLEBARINFO()
     #ti.cbSize = sizeof(ti)
     #GetTitleBarInfo(hwnd, byref(ti))
     #if ti.rgstate[0] & win32con.STATE_SYSTEM_INVISIBLE:
     #    log("skipped system invisible window")
     #    return True
     w = right-left
     h = bottom-top
     l("shape(%s - %#x)=%s", window_title, hwnd, (left, top, w, h))
     if w<=0 and h<=0:
         l("skipped invalid window size: %ix%i", w, h)
         return True
     if left==-32000 and top==-32000:
         #there must be a better way of skipping those - I haven't found it
         l("skipped special window")
         return True
     #now clip rectangle:
     if left<0:
         left = 0
         w = right
     if top<0:
         top = 0
         h = bottom
     rectangles.append((left, top, w, h))
     return True
Exemplo n.º 37
0
def listComPorts(onlyAvailable=True):
	"""List com ports on the system.
	@param onlyAvailable: Only return ports that are currently available.
	@type onlyAvailable: bool
	@return: Dicts including keys of port, friendlyName and hardwareID.
	@rtype: generator of dict
	"""
	flags = DIGCF_DEVICEINTERFACE
	if onlyAvailable:
		flags |= DIGCF_PRESENT

	buf = ctypes.create_unicode_buffer(1024)
	g_hdi = SetupDiGetClassDevs(ctypes.byref(GUID_CLASS_COMPORT), None, NULL, flags)
	try:
		for dwIndex in xrange(256):
			entry = {}
			did = SP_DEVICE_INTERFACE_DATA()
			did.cbSize = ctypes.sizeof(did)

			if not SetupDiEnumDeviceInterfaces(
				g_hdi,
				None,
				ctypes.byref(GUID_CLASS_COMPORT),
				dwIndex,
				ctypes.byref(did)
			):
				if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS:
					raise ctypes.WinError()
				break

			dwNeeded = DWORD()
			# get the size
			if not SetupDiGetDeviceInterfaceDetail(
				g_hdi,
				ctypes.byref(did),
				None, 0, ctypes.byref(dwNeeded),
				None
			):
				# Ignore ERROR_INSUFFICIENT_BUFFER
				if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
					raise ctypes.WinError()
			# allocate buffer
			class SP_DEVICE_INTERFACE_DETAIL_DATA_W(ctypes.Structure):
				_fields_ = (
					('cbSize', DWORD),
					('DevicePath', WCHAR*(dwNeeded.value - ctypes.sizeof(DWORD))),
				)
				def __str__(self):
					return "DevicePath:%s" % (self.DevicePath,)
			idd = SP_DEVICE_INTERFACE_DETAIL_DATA_W()
			idd.cbSize = SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_W
			devinfo = SP_DEVINFO_DATA()
			devinfo.cbSize = ctypes.sizeof(devinfo)
			if not SetupDiGetDeviceInterfaceDetail(
				g_hdi,
				ctypes.byref(did),
				ctypes.byref(idd), dwNeeded, None,
				ctypes.byref(devinfo)
			):
				raise ctypes.WinError()

			# hardware ID
			if not SetupDiGetDeviceRegistryProperty(
				g_hdi,
				ctypes.byref(devinfo),
				SPDRP_HARDWAREID,
				None,
				ctypes.byref(buf), ctypes.sizeof(buf) - 1,
				None
			):
				# Ignore ERROR_INSUFFICIENT_BUFFER
				if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
					raise ctypes.WinError()
			else:
				hwID = entry["hardwareID"] = buf.value

			regKey = ctypes.windll.setupapi.SetupDiOpenDevRegKey(g_hdi, ctypes.byref(devinfo), DICS_FLAG_GLOBAL, 0, DIREG_DEV, winreg.KEY_READ)
			try:
				try:
					port = entry["port"] = winreg.QueryValueEx(regKey, "PortName")[0]
				except WindowsError:
					# #6015: In some rare cases, this value doesn't exist.
					log.debugWarning("No PortName value for hardware ID %s" % hwID)
					continue
				if not port:
					log.debugWarning("Empty PortName value for hardware ID %s" % hwID)
					continue
				if hwID.startswith("BTHENUM\\"):
					# This is a Microsoft bluetooth port.
					try:
						addr = winreg.QueryValueEx(regKey, "Bluetooth_UniqueID")[0].split("#", 1)[1].split("_", 1)[0]
						addr = int(addr, 16)
						entry["bluetoothAddress"] = addr
						if addr:
							entry["bluetoothName"] = getBluetoothDeviceInfo(addr).szName
					except:
						pass
				elif hwID == r"Bluetooth\0004&0002":
					# This is a Toshiba bluetooth port.
					try:
						entry["bluetoothAddress"], entry["bluetoothName"] = getToshibaBluetoothPortInfo(port)
					except:
						pass
				elif hwID == r"{95C7A0A0-3094-11D7-A202-00508B9D7D5A}\BLUETOOTHPORT":
					try:
						entry["bluetoothAddress"], entry["bluetoothName"] = getWidcommBluetoothPortInfo(port)
					except:
						pass
				elif "USB" in hwID or "FTDIBUS" in hwID:
					usbIDStart = hwID.find("VID_")
					if usbIDStart==-1:
						continue
					usbID = entry['usbID'] = hwID[usbIDStart:usbIDStart+17] # VID_xxxx&PID_xxxx
			finally:
				ctypes.windll.advapi32.RegCloseKey(regKey)

			# friendly name
			if not SetupDiGetDeviceRegistryProperty(
				g_hdi,
				ctypes.byref(devinfo),
				SPDRP_FRIENDLYNAME,
				None,
				ctypes.byref(buf), ctypes.sizeof(buf) - 1,
				None
			):
				# #6007: SPDRP_FRIENDLYNAME sometimes doesn't exist/isn't valid.
				log.debugWarning("Couldn't get SPDRP_FRIENDLYNAME for %r: %s" % (port, ctypes.WinError()))
				entry["friendlyName"] = port
			else:
				entry["friendlyName"] = buf.value

			if _isDebug():
				log.debug("%r" % entry)
			yield entry

	finally:
		SetupDiDestroyDeviceInfoList(g_hdi)
	if _isDebug():
		log.debug("Finished listing com ports")
Exemplo n.º 38
0
def iterate_comports():
    """Return a generator that yields descriptions for serial ports"""
    PortsGUIDs = (GUID *
                  8)()  # so far only seen one used, so hope 8 are enough...
    ports_guids_size = DWORD()
    if not SetupDiClassGuidsFromName("Ports", PortsGUIDs,
                                     ctypes.sizeof(PortsGUIDs),
                                     ctypes.byref(ports_guids_size)):
        raise ctypes.WinError()

    ModemsGUIDs = (GUID *
                   8)()  # so far only seen one used, so hope 8 are enough...
    modems_guids_size = DWORD()
    if not SetupDiClassGuidsFromName("Modem", ModemsGUIDs,
                                     ctypes.sizeof(ModemsGUIDs),
                                     ctypes.byref(modems_guids_size)):
        raise ctypes.WinError()

    GUIDs = PortsGUIDs[:ports_guids_size.
                       value] + ModemsGUIDs[:modems_guids_size.value]

    # repeat for all possible GUIDs
    for index in range(len(GUIDs)):
        bInterfaceNumber = None
        g_hdi = SetupDiGetClassDevs(
            ctypes.byref(GUIDs[index]), None, NULL, DIGCF_PRESENT
        )  # was DIGCF_PRESENT|DIGCF_DEVICEINTERFACE which misses CDC ports

        devinfo = SP_DEVINFO_DATA()
        devinfo.cbSize = ctypes.sizeof(devinfo)
        index = 0
        while SetupDiEnumDeviceInfo(g_hdi, index, ctypes.byref(devinfo)):
            index += 1

            # get the real com port name
            hkey = SetupDiOpenDevRegKey(
                g_hdi,
                ctypes.byref(devinfo),
                DICS_FLAG_GLOBAL,
                0,
                DIREG_DEV,  # DIREG_DRV for SW info
                KEY_READ)
            port_name_buffer = ctypes.create_unicode_buffer(250)
            port_name_length = ULONG(ctypes.sizeof(port_name_buffer))
            RegQueryValueEx(hkey, "PortName", None, None,
                            ctypes.byref(port_name_buffer),
                            ctypes.byref(port_name_length))
            RegCloseKey(hkey)

            # unfortunately does this method also include parallel ports.
            # we could check for names starting with COM or just exclude LPT
            # and hope that other "unknown" names are serial ports...
            if port_name_buffer.value.startswith('LPT'):
                continue

            # hardware ID
            szHardwareID = ctypes.create_unicode_buffer(250)
            # try to get ID that includes serial number
            if not SetupDiGetDeviceInstanceId(
                    g_hdi,
                    ctypes.byref(devinfo),
                    #~ ctypes.byref(szHardwareID),
                    szHardwareID,
                    ctypes.sizeof(szHardwareID) - 1,
                    None):
                # fall back to more generic hardware ID if that would fail
                if not SetupDiGetDeviceRegistryProperty(
                        g_hdi, ctypes.byref(devinfo), SPDRP_HARDWAREID, None,
                        ctypes.byref(szHardwareID),
                        ctypes.sizeof(szHardwareID) - 1, None):
                    # Ignore ERROR_INSUFFICIENT_BUFFER
                    if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
                        raise ctypes.WinError()
            # stringify
            szHardwareID_str = szHardwareID.value

            info = list_ports_common.ListPortInfo(port_name_buffer.value,
                                                  skip_link_detection=True)

            # in case of USB, make a more readable string, similar to that form
            # that we also generate on other platforms
            if szHardwareID_str.startswith('USB'):
                m = re.search(
                    r'VID_([0-9a-f]{4})(&PID_([0-9a-f]{4}))?(&MI_(\d{2}))?(\\(.*))?',
                    szHardwareID_str, re.I)
                if m:
                    info.vid = int(m.group(1), 16)
                    if m.group(3):
                        info.pid = int(m.group(3), 16)
                    if m.group(5):
                        bInterfaceNumber = int(m.group(5))

                    # Check that the USB serial number only contains alphanumeric characters. It
                    # may be a windows device ID (ephemeral ID) for composite devices.
                    if m.group(7) and re.match(r'^\w+$', m.group(7)):
                        info.serial_number = m.group(7)
                    else:
                        info.serial_number = get_parent_serial_number(
                            devinfo.DevInst, info.vid, info.pid)

                # calculate a location string
                loc_path_str = ctypes.create_unicode_buffer(250)
                if SetupDiGetDeviceRegistryProperty(
                        g_hdi, ctypes.byref(devinfo), SPDRP_LOCATION_PATHS,
                        None, ctypes.byref(loc_path_str),
                        ctypes.sizeof(loc_path_str) - 1, None):
                    m = re.finditer(r'USBROOT\((\w+)\)|#USB\((\w+)\)',
                                    loc_path_str.value)
                    location = []
                    for g in m:
                        if g.group(1):
                            location.append('{:d}'.format(int(g.group(1)) + 1))
                        else:
                            if len(location) > 1:
                                location.append('.')
                            else:
                                location.append('-')
                            location.append(g.group(2))
                    if bInterfaceNumber is not None:
                        location.append(':{}.{}'.format(
                            'x',  # XXX how to determine correct bConfigurationValue?
                            bInterfaceNumber))
                    if location:
                        info.location = ''.join(location)
                info.hwid = info.usb_info()
            elif szHardwareID_str.startswith('FTDIBUS'):
                m = re.search(
                    r'VID_([0-9a-f]{4})\+PID_([0-9a-f]{4})(\+(\w+))?',
                    szHardwareID_str, re.I)
                if m:
                    info.vid = int(m.group(1), 16)
                    info.pid = int(m.group(2), 16)
                    if m.group(4):
                        info.serial_number = m.group(4)
                # USB location is hidden by FDTI driver :(
                info.hwid = info.usb_info()
            else:
                info.hwid = szHardwareID_str

            # friendly name
            szFriendlyName = ctypes.create_unicode_buffer(250)
            if SetupDiGetDeviceRegistryProperty(
                    g_hdi,
                    ctypes.byref(devinfo),
                    SPDRP_FRIENDLYNAME,
                    #~ SPDRP_DEVICEDESC,
                    None,
                    ctypes.byref(szFriendlyName),
                    ctypes.sizeof(szFriendlyName) - 1,
                    None):
                info.description = szFriendlyName.value
            #~ else:
            # Ignore ERROR_INSUFFICIENT_BUFFER
            #~ if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
            #~ raise IOError("failed to get details for %s (%s)" % (devinfo, szHardwareID.value))
            # ignore errors and still include the port in the list, friendly name will be same as port name

            # manufacturer
            szManufacturer = ctypes.create_unicode_buffer(250)
            if SetupDiGetDeviceRegistryProperty(
                    g_hdi,
                    ctypes.byref(devinfo),
                    SPDRP_MFG,
                    #~ SPDRP_DEVICEDESC,
                    None,
                    ctypes.byref(szManufacturer),
                    ctypes.sizeof(szManufacturer) - 1,
                    None):
                info.manufacturer = szManufacturer.value
            yield info
        SetupDiDestroyDeviceInfoList(g_hdi)
Exemplo n.º 39
0
def wtinfo_string(category, index):
    size = lib.WTInfoW(category, index, None)
    buffer = ctypes.create_unicode_buffer(size)
    lib.WTInfoW(category, index, buffer)
    return buffer.value
Exemplo n.º 40
0
def get_parent_serial_number(child_devinst,
                             child_vid,
                             child_pid,
                             depth=0,
                             last_serial_number=None):
    """ Get the serial number of the parent of a device.

    Args:
        child_devinst: The device instance handle to get the parent serial number of.
        child_vid: The vendor ID of the child device.
        child_pid: The product ID of the child device.
        depth: The current iteration depth of the USB device tree.
    """

    # If the traversal depth is beyond the max, abandon attempting to find the serial number.
    if depth > MAX_USB_DEVICE_TREE_TRAVERSAL_DEPTH:
        return '' if not last_serial_number else last_serial_number

    # Get the parent device instance.
    devinst = DWORD()
    ret = CM_Get_Parent(ctypes.byref(devinst), child_devinst, 0)

    if ret:
        win_error = CM_MapCrToWin32Err(DWORD(ret), DWORD(0))

        # If there is no parent available, the child was the root device. We cannot traverse
        # further.
        if win_error == ERROR_NOT_FOUND:
            return '' if not last_serial_number else last_serial_number

        raise ctypes.WinError(win_error)

    # Get the ID of the parent device and parse it for vendor ID, product ID, and serial number.
    parentHardwareID = ctypes.create_unicode_buffer(250)

    ret = CM_Get_Device_IDW(devinst, parentHardwareID,
                            ctypes.sizeof(parentHardwareID) - 1, 0)

    if ret:
        raise ctypes.WinError(CM_MapCrToWin32Err(DWORD(ret), DWORD(0)))

    parentHardwareID_str = parentHardwareID.value
    m = re.search(
        r'VID_([0-9a-f]{4})(&PID_([0-9a-f]{4}))?(&MI_(\d{2}))?(\\(.*))?',
        parentHardwareID_str, re.I)

    # return early if we have no matches (likely malformed serial, traversed too far)
    if not m:
        return '' if not last_serial_number else last_serial_number

    vid = None
    pid = None
    serial_number = None
    if m.group(1):
        vid = int(m.group(1), 16)
    if m.group(3):
        pid = int(m.group(3), 16)
    if m.group(7):
        serial_number = m.group(7)

    # store what we found as a fallback for malformed serial values up the chain
    found_serial_number = serial_number

    # Check that the USB serial number only contains alphanumeric characters. It may be a windows
    # device ID (ephemeral ID).
    if serial_number and not re.match(r'^\w+$', serial_number):
        serial_number = None

    if not vid or not pid:
        # If pid and vid are not available at this device level, continue to the parent.
        return get_parent_serial_number(devinst, child_vid, child_pid,
                                        depth + 1, found_serial_number)

    if pid != child_pid or vid != child_vid:
        # If the VID or PID has changed, we are no longer looking at the same physical device. The
        # serial number is unknown.
        return '' if not last_serial_number else last_serial_number

    # In this case, the vid and pid of the parent device are identical to the child. However, if
    # there still isn't a serial number available, continue to the next parent.
    if not serial_number:
        return get_parent_serial_number(devinst, child_vid, child_pid,
                                        depth + 1, found_serial_number)

    # Finally, the VID and PID are identical to the child and a serial number is present, so return
    # it.
    return serial_number
Exemplo n.º 41
0
def _winmm_errcheck(res, func, args):
    if res != MMSYSERR_NOERROR:
        buf = create_unicode_buffer(256)
        winmm.waveOutGetErrorTextW(res, buf, sizeof(buf))
        raise WindowsError(res, buf.value)
Exemplo n.º 42
0
        def __init__(self):

            self.app_dir = join(KnownFolderPath(FOLDERID_LocalAppData),
                                appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.internal_plugin_dir = join(
                dirname(
                    getattr(sys, 'frozen', False)
                    and sys.executable.decode(sys.getfilesystemencoding())
                    or __file__), u'plugins')

            # expanduser in Python 2 on Windows doesn't handle non-ASCII - http://bugs.python.org/issue13207
            self.home = KnownFolderPath(FOLDERID_Profile) or u'\\'

            journaldir = KnownFolderPath(FOLDERID_SavedGames)
            self.default_journal_dir = journaldir and join(
                journaldir, 'Frontier Developments', 'Elite Dangerous') or None

            self.default_interaction_dir = join(
                KnownFolderPath(FOLDERID_LocalAppData),
                'Frontier Developments', 'Elite Dangerous', 'CommanderHistory')

            self.respath = dirname(
                getattr(sys, 'frozen', False)
                and sys.executable.decode(sys.getfilesystemencoding())
                or __file__)

            self.identifier = applongname

            self.hkey = HKEY()
            disposition = DWORD()
            if RegCreateKeyEx(HKEY_CURRENT_USER,
                              r'Software\Marginal\EDMarketConnector', 0, None,
                              0, KEY_ALL_ACCESS, None, ctypes.byref(self.hkey),
                              ctypes.byref(disposition)):
                raise Exception()

            if disposition.value == REG_CREATED_NEW_KEY:

                # Migrate pre-1.3.4 registry location
                oldkey = HKEY()
                if not RegOpenKeyEx(HKEY_CURRENT_USER,
                                    r'Software\EDMarketConnector', 0,
                                    KEY_ALL_ACCESS, ctypes.byref(oldkey)):
                    RegCopyTree(oldkey, None, self.hkey)
                    RegCloseKey(oldkey)
                    RegDeleteKey(HKEY_CURRENT_USER,
                                 r'Software\EDMarketConnector')

                # set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings
                sparklekey = HKEY()
                if not RegCreateKeyEx(self.hkey, 'WinSparkle', 0, None, 0,
                                      KEY_ALL_ACCESS, None,
                                      ctypes.byref(sparklekey),
                                      ctypes.byref(disposition)):
                    if disposition.value == REG_CREATED_NEW_KEY:
                        buf = ctypes.create_unicode_buffer('1')
                        RegSetValueEx(sparklekey, 'CheckForUpdates', 0, 1, buf,
                                      len(buf) * 2)
                        buf = ctypes.create_unicode_buffer(
                            unicode(update_interval))
                        RegSetValueEx(sparklekey, 'UpdateInterval', 0, 1, buf,
                                      len(buf) * 2)
                    RegCloseKey(sparklekey)

            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir', KnownFolderPath(FOLDERID_Documents))
Exemplo n.º 43
0
def listUsbDevices(onlyAvailable=True):
	"""List USB devices on the system.
	@param onlyAvailable: Only return devices that are currently available.
	@type onlyAvailable: bool
	@return: Generates dicts including keys of usbID (VID and PID), devicePath and hardwareID.
	@rtype: generator of dict
	"""
	flags = DIGCF_DEVICEINTERFACE
	if onlyAvailable:
		flags |= DIGCF_PRESENT

	buf = ctypes.create_unicode_buffer(1024)
	g_hdi = SetupDiGetClassDevs(GUID_DEVINTERFACE_USB_DEVICE, None, NULL, flags)
	try:
		for dwIndex in xrange(256):
			did = SP_DEVICE_INTERFACE_DATA()
			did.cbSize = ctypes.sizeof(did)

			if not SetupDiEnumDeviceInterfaces(
				g_hdi,
				None,
				GUID_DEVINTERFACE_USB_DEVICE,
				dwIndex,
				ctypes.byref(did)
			):
				if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS:
					raise ctypes.WinError()
				break

			dwNeeded = DWORD()
			# get the size
			if not SetupDiGetDeviceInterfaceDetail(
				g_hdi,
				ctypes.byref(did),
				None, 0, ctypes.byref(dwNeeded),
				None
			):
				# Ignore ERROR_INSUFFICIENT_BUFFER
				if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
					raise ctypes.WinError()
			# allocate buffer
			class SP_DEVICE_INTERFACE_DETAIL_DATA_W(ctypes.Structure):
				_fields_ = (
					('cbSize', DWORD),
					('DevicePath', WCHAR*(dwNeeded.value - ctypes.sizeof(DWORD))),
				)
				def __str__(self):
					return "DevicePath:%s" % (self.DevicePath,)
			idd = SP_DEVICE_INTERFACE_DETAIL_DATA_W()
			idd.cbSize = SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_W
			devinfo = SP_DEVINFO_DATA()
			devinfo.cbSize = ctypes.sizeof(devinfo)
			if not SetupDiGetDeviceInterfaceDetail(
				g_hdi,
				ctypes.byref(did),
				ctypes.byref(idd), dwNeeded, None,
				ctypes.byref(devinfo)
			):
				raise ctypes.WinError()

			# hardware ID
			if not SetupDiGetDeviceRegistryProperty(
				g_hdi,
				ctypes.byref(devinfo),
				SPDRP_HARDWAREID,
				None,
				ctypes.byref(buf), ctypes.sizeof(buf) - 1,
				None
			):
				# Ignore ERROR_INSUFFICIENT_BUFFER
				if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
					raise ctypes.WinError()
			else:
				# The string is of the form "usb\VID_xxxx&PID_xxxx&..."
				usbId = buf.value[4:21] # VID_xxxx&PID_xxxx
				info = {
					"hardwareID": buf.value,
					"usbID": usbId,
					"devicePath": idd.DevicePath}
				if _isDebug():
					log.debug("%r" % usbId)
				yield info
	finally:
		SetupDiDestroyDeviceInfoList(g_hdi)
	if _isDebug():
		log.debug("Finished listing USB devices")
Exemplo n.º 44
0
 def GetSystemDirectory():
     buffer = create_unicode_buffer(MAX_PATH + 1)
     GetSystemDirectoryW(buffer, len(buffer))
     return buffer.value
def decrypt(key, message, algorithm, iv=None):
    if algorithm == ENCRYPT_NONE:
        return message
    elif algorithm == ENCRYPT_RC4:
        ctx = ctypes.create_unicode_buffer(140)
        addressgen.ssl_library.EVP_CIPHER_CTX_init(ctx)

        key_length = len(key)
        cipher = addressgen.ssl_library.EVP_rc4()

        # First configure parameters
        r = addressgen.ssl_library.EVP_DecryptInit_ex(ctx, cipher, None, None,
                                                      None)
        if r == 0:
            raise Exception("EncryptInit failed")

        addressgen.ssl_library.EVP_CIPHER_CTX_set_key_length(ctx, key_length)

        # Then reinit..
        iv = ctypes.create_string_buffer(b'\x00' * 16)
        r = addressgen.ssl_library.EVP_DecryptInit_ex(ctx, None, None,
                                                      ctypes.c_char_p(key), iv)
        if r == 0:
            raise Exception("DecryptInit failed")

        addressgen.ssl_library.EVP_CIPHER_CTX_set_padding(ctx, 1)

        block_size = addressgen.ssl_library.EVP_CIPHER_block_size(cipher)

        outlen = ctypes.c_int(len(message) + block_size)
        out = ctypes.create_string_buffer(b'\x00' * outlen.value)

        r = addressgen.ssl_library.EVP_DecryptUpdate(ctx, out,
                                                     ctypes.byref(outlen),
                                                     ctypes.c_char_p(message),
                                                     len(message))
        if r == 0:
            raise Exception("DecryptUpdate failed")

        out2 = ctypes.create_string_buffer(b'\x00' * block_size)
        outlen2 = ctypes.c_int(block_size)
        r = addressgen.ssl_library.EVP_DecryptFinal_ex(ctx, out2,
                                                       ctypes.byref(outlen2))

        addressgen.ssl_library.EVP_CIPHER_CTX_cleanup(ctx)
        return out[:outlen.value] + out2[:outlen2.value]
    elif algorithm == ENCRYPT_AES128 or algorithm == ENCRYPT_AES256:
        ctx = ctypes.create_unicode_buffer(140)
        addressgen.ssl_library.EVP_CIPHER_CTX_init(ctx)

        key_length = len(key)
        if algorithm == ENCRYPT_AES128:
            cipher = addressgen.ssl_library.EVP_aes_128_cbc()
            assert key_length == 16
        else:
            cipher = addressgen.ssl_library.EVP_aes_256_cbc()
            assert key_length == 32

        # First configure parameters
        r = addressgen.ssl_library.EVP_DecryptInit_ex(ctx, cipher, None, None,
                                                      None)
        if r == 0:
            raise Exception("EncryptInit failed")

        addressgen.ssl_library.EVP_CIPHER_CTX_set_key_length(ctx, key_length)

        # Then reinit..
        assert iv is not None and len(iv) == key_length
        iv = ctypes.create_string_buffer(iv)
        r = addressgen.ssl_library.EVP_DecryptInit_ex(ctx, None, None,
                                                      ctypes.c_char_p(key), iv)
        if r == 0:
            raise Exception("DecryptInit failed")

        addressgen.ssl_library.EVP_CIPHER_CTX_set_padding(ctx, 1)

        block_size = addressgen.ssl_library.EVP_CIPHER_block_size(cipher)

        outlen = ctypes.c_int(len(message) + block_size)
        out = ctypes.create_string_buffer(b'\x00' * outlen.value)

        r = addressgen.ssl_library.EVP_DecryptUpdate(ctx, out,
                                                     ctypes.byref(outlen),
                                                     ctypes.c_char_p(message),
                                                     len(message))
        if r == 0:
            raise Exception("DecryptUpdate failed")

        out2 = ctypes.create_string_buffer(b'\x00' * block_size)
        outlen2 = ctypes.c_int(block_size)
        r = addressgen.ssl_library.EVP_DecryptFinal_ex(ctx, out2,
                                                       ctypes.byref(outlen2))

        addressgen.ssl_library.EVP_CIPHER_CTX_cleanup(ctx)
        return out[:outlen.value] + out2[:outlen2.value]
    elif algorithm == ENCRYPT_RSA:
        rsa_size = addressgen.ssl_library.RSA_size(key.rsa)
        buf = ctypes.create_string_buffer(rsa_size)

        ## flen must be ... less than RSA_size(rsa) - 41 for RSA_PKCS1_OAEP_PADDING
        #if len(message) > (rsa_size - 41):
        #    raise Exception("RSA can only encrypt messages less than the key size")

        decrypt_len = addressgen.ssl_library.RSA_private_decrypt(
            len(message), ctypes.c_char_p(message), buf, key.rsa,
            RSA_PKCS1_OAEP_PADDING)
        if decrypt_len == -1:
            raise Exception("RSA encryption failed")

        return buf[:decrypt_len]
Exemplo n.º 46
0
def listHidDevices(onlyAvailable=True):
	"""List HID devices on the system.
	@param onlyAvailable: Only return devices that are currently available.
	@type onlyAvailable: bool
	@return: Generates dicts including keys such as hardwareID,
		usbID (in the form "VID_xxxx&PID_xxxx")
		and devicePath.
	@rtype: generator of dict
	"""
	global _hidGuid
	if not _hidGuid:
		_hidGuid = GUID()
		ctypes.windll.hid.HidD_GetHidGuid(ctypes.byref(_hidGuid))

	flags = DIGCF_DEVICEINTERFACE
	if onlyAvailable:
		flags |= DIGCF_PRESENT

	buf = ctypes.create_unicode_buffer(1024)
	g_hdi = SetupDiGetClassDevs(_hidGuid, None, NULL, flags)
	try:
		for dwIndex in xrange(256):
			did = SP_DEVICE_INTERFACE_DATA()
			did.cbSize = ctypes.sizeof(did)

			if not SetupDiEnumDeviceInterfaces(
				g_hdi,
				None,
				_hidGuid,
				dwIndex,
				ctypes.byref(did)
			):
				if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS:
					raise ctypes.WinError()
				break

			dwNeeded = DWORD()
			# get the size
			if not SetupDiGetDeviceInterfaceDetail(
				g_hdi,
				ctypes.byref(did),
				None, 0, ctypes.byref(dwNeeded),
				None
			):
				# Ignore ERROR_INSUFFICIENT_BUFFER
				if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
					raise ctypes.WinError()
			# allocate buffer
			class SP_DEVICE_INTERFACE_DETAIL_DATA_W(ctypes.Structure):
				_fields_ = (
					('cbSize', DWORD),
					('DevicePath', WCHAR*(dwNeeded.value - ctypes.sizeof(DWORD))),
				)
				def __str__(self):
					return "DevicePath:%s" % (self.DevicePath,)
			idd = SP_DEVICE_INTERFACE_DETAIL_DATA_W()
			idd.cbSize = SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_W
			devinfo = SP_DEVINFO_DATA()
			devinfo.cbSize = ctypes.sizeof(devinfo)
			if not SetupDiGetDeviceInterfaceDetail(
				g_hdi,
				ctypes.byref(did),
				ctypes.byref(idd), dwNeeded, None,
				ctypes.byref(devinfo)
			):
				raise ctypes.WinError()

			# hardware ID
			if not SetupDiGetDeviceRegistryProperty(
				g_hdi,
				ctypes.byref(devinfo),
				SPDRP_HARDWAREID,
				None,
				ctypes.byref(buf), ctypes.sizeof(buf) - 1,
				None
			):
				# Ignore ERROR_INSUFFICIENT_BUFFER
				if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
					raise ctypes.WinError()
			else:
				hwId = buf.value
				info = _getHidInfo(hwId, idd.DevicePath)
				if _isDebug():
					log.debug("%r" % info)
				yield info
	finally:
		SetupDiDestroyDeviceInfoList(g_hdi)
	if _isDebug():
		log.debug("Finished listing HID devices")
Exemplo n.º 47
0
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
Exemplo n.º 48
0
    def __init__(self, layout_id=None, debug=False):
        if layout_id is None:
            layout_id = KeyboardLayout.current_layout_id()
        self.layout_id = layout_id

        # Find virtual key code for each scan code (if any).
        sc_to_vk = {}
        vk_to_sc = {}
        for sc in range(0x01, 0x7f + 1):
            vk = MapVirtualKeyEx(sc, 3, layout_id)
            if vk != 0:
                sc_to_vk[sc] = vk
                vk_to_sc[vk] = sc

        state = (wintypes.BYTE * 256)()
        strbuf = ctypes.create_unicode_buffer(8)

        def fill_state(ss):
            for mod_state, mod_vk in (
                (SHIFT_STATE.SHIFT, VK.SHIFT),
                (SHIFT_STATE.CTRL, VK.CONTROL),
                (SHIFT_STATE.MENU, VK.MENU),
            ):
                state[mod_vk] = 0x80 if (ss & mod_state) != 0 else 0

        def to_unichr(vk, sc, ss):
            fill_state(ss)
            rc = ToUnicodeEx(vk, sc, state, strbuf, len(strbuf), 0, layout_id)
            if rc > 0:
                dead_key = False
                char = ctypes.wstring_at(strbuf.value, rc)
            elif rc < 0:
                # Dead key, flush state.
                dead_key = True
                fill_state(0)
                rc = ToUnicodeEx(VK.SPACE, vk_to_sc[VK.SPACE], state, strbuf,
                                 len(strbuf), 0, layout_id)
                char = ctypes.wstring_at(strbuf.value, rc) if rc > 0 else ''
            else:
                dead_key = False
                char = ''
            return char, dead_key

        def sort_vk_ss_list(vk_ss_list):
            # Prefer lower modifiers combo.
            return sorted(vk_ss_list, key=lambda vk_ss: popcount_8(vk_ss[1]))

        char_to_vk_ss = defaultdict(list)
        keyname_to_vk = defaultdict(list)

        for sc, vk in sorted(sc_to_vk.items()):
            for ss in SHIFT_STATE:
                if ss in (SHIFT_STATE.MENU, SHIFT_STATE.SHIFT_MENU):
                    # Alt and Shift+Alt don't work, so skip them.
                    continue
                char, dead_key = to_unichr(vk, sc, ss)
                if debug and char:
                    print('%s%s -> %s [%r] %s' % (
                        shift_state_str(ss),
                        vk_to_str(vk),
                        char,
                        char,
                        '[dead key]' if dead_key else '',
                    ))
                kn = None
                if char:
                    kn = CHAR_TO_KEYNAME.get(char)
                    if dead_key:
                        kn = kn and DEAD_KEYNAME.get(kn, 'dead_' + kn)
                    else:
                        char_to_vk_ss[char].append((vk, ss))
                    if kn:
                        keyname_to_vk[kn].append((vk, ss))

        self.char_to_vk_ss = {
            char: sort_vk_ss_list(vk_ss_list)[0]
            for char, vk_ss_list in char_to_vk_ss.items()
        }
        self.char_to_vk_ss['\n'] = self.char_to_vk_ss['\r']

        self.keyname_to_vk = {kn: vk for vk, kn in VK_TO_KEYNAME.items()}
        self.keyname_to_vk.update({
            'next': VK.NEXT,
            'prior': VK.PRIOR,
            'kp_delete': VK.DELETE,
            'kp_enter': VK.RETURN,
            'break': VK.CANCEL,
        })
        self.keyname_to_vk.update({
            kn: sort_vk_ss_list(vk_ss_list)[0][0]
            for kn, vk_ss_list in keyname_to_vk.items()
        })
        add_modifiers_aliases(self.keyname_to_vk)

        self.ss_to_vks = {}
        for ss in SHIFT_STATE:
            vk_list = []
            for mod_state, mod_vk in (
                (SHIFT_STATE.SHIFT, VK.SHIFT),
                (SHIFT_STATE.CTRL, VK.CONTROL),
                (SHIFT_STATE.MENU, VK.MENU),
            ):
                if (ss & mod_state) != 0:
                    vk_list.append(mod_vk)
            self.ss_to_vks[ss] = tuple(vk_list)
Exemplo n.º 49
0
    def _show_toast(self, title, msg, icon_path, delay, sound_path, tooltip,
                    duration, callback_on_click, kill_without_click):
        """Notification settings.

        :title: notification title
        :msg: notification message
        :icon_path: path to the .ico file to custom notification
        :delay: delay in seconds before notification self-destruction, None for no-self-destruction
        :sound_path: path to the .wav file to custom notification
        :duration: how long the notification stays on the screen in seconds
        :callback_on_click: function to run on click
        :kill_without_click: Kill the tray icon after the notification goes away, even if it wasn't clicked
        """
        self.delay = delay
        self.destroy_window = kill_without_click

        # Register the window class.
        self.wc = WNDCLASS()
        self.hinst = self.wc.hInstance = GetModuleHandle(None)
        self.wc.lpszClassName = str(
            f"PythonTaskbar - {uuid4().hex}")  # must be a string
        self.wc.lpfnWndProc = self._decorator(
            self.wnd_proc,
            callback_on_click)  # could instead specify simple mapping
        try:
            self.classAtom = RegisterClass(self.wc)
        except Exception as e:
            raise type(e)(f"Some trouble with classAtom:\n{e}") from None
        style = WS_OVERLAPPED | WS_SYSMENU
        self.hwnd = CreateWindow(self.classAtom, "Python Taskbar", style, 0, 0,
                                 CW_USEDEFAULT, CW_USEDEFAULT, 0, 0,
                                 self.hinst, None)
        UpdateWindow(self.hwnd)

        # icon
        if icon_path is not None:
            icon_path = path.realpath(icon_path)
        else:
            icon_path = resource_filename(Requirement.parse("win10toast"),
                                          "win10toast/data/python.ico")
        icon_flags = LR_LOADFROMFILE | LR_DEFAULTSIZE
        try:
            hicon = LoadImage(self.hinst, icon_path, IMAGE_ICON, 0, 0,
                              icon_flags)
        except Exception as e:
            raise type(e)(
                f"Some trouble with the icon ({icon_path}):\n{e}") from None
            hicon = LoadIcon(0, IDI_APPLICATION)

        # set the duration
        buff = create_unicode_buffer(10)
        SystemParametersInfoW(SPI_GETMESSAGEDURATION, 0, buff, 0)
        try:
            oldlength = int(
                buff.value.encode('unicode_escape').decode().replace(
                    "\\", "0"), 16)
        except ValueError:
            oldlength = 5  # default notification length

        durationOutput = SystemParametersInfoW(SPI_SETMESSAGEDURATION, 0,
                                               duration, SPIF_SENDCHANGE)
        SystemParametersInfoW(SPI_GETMESSAGEDURATION, 0, buff, 0)

        durationError = False
        try:
            int(
                buff.value.encode('unicode_escape').decode().replace(
                    "\\", "0"), 16)
        except ValueError:
            durationError = True
        if durationOutput == 0 or duration > 255 or durationError:
            SystemParametersInfoW(SPI_SETMESSAGEDURATION, 0, oldlength,
                                  SPIF_SENDCHANGE)
            raise RuntimeError(
                f"Some trouble with the duration ({duration}): Invalid duration length"
            )

        # Taskbar icon
        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
        nid = (self.hwnd, 0, flags, WM_USER + 20, hicon, tooltip)

        Shell_NotifyIcon(NIM_ADD, nid)
        Shell_NotifyIcon(
            NIM_MODIFY,
            (self.hwnd, 0, NIF_INFO, WM_USER + 20, hicon, tooltip, msg, 0,
             title, 0 if sound_path == None else NIIF_NOSOUND))

        # play the custom sound
        if sound_path is not None:
            sound_path = path.realpath(sound_path)
            if not path.exists(sound_path):
                raise IOError(
                    "Some trouble with the sound file ({sound_path}): [Errno 2] No such file"
                )

            try:
                PlaySound(sound_path, SND_FILENAME)
            except Exception as e:
                raise type(
                    e)(f"Some trouble with the sound file ({sound_path}): {e}"
                       ) from None

        PumpMessages()
        # put the notification duration back to normal
        SystemParametersInfoW(SPI_SETMESSAGEDURATION, 0, oldlength,
                              SPIF_SENDCHANGE)

        # take a rest then destroy
        if self.delay is not None and self.destroy_window:
            while self.delay > 0:
                sleep(0.1)
                self.delay -= 0.1

            DestroyWindow(self.hwnd)
            UnregisterClass(self.wc.lpszClassName, self.hinst)
            try:  # sometimes the tray icon sticks around until you click it - this should stop it
                self.remove_window(self.hwnd)
            except WinTypesException:
                pass
        return
Exemplo n.º 50
0
    'sles': '12',
    'centos': '7',
    'debian': '8',
    'fedora': '23',
    'suse': '42.1',
    'ubuntu': '14.04'
}
DISTRO_NAME = ''
DISTRO_VER = ''

VSCODE_HOMEPATH = os.path.expanduser('~')

if PLAT == 'Windows':
    from knownfolders import get_folder_path, FOLDERID
    _kernel32 = ctypes.windll.kernel32
    _windir = ctypes.create_unicode_buffer(1024)
    _kernel32.GetWindowsDirectoryW(_windir, 1024)
    _windrive = _windir.value[:3]
    _fallback = os.path.join(_windrive, 'Program Files (x86)')
    PROGRAM_FILES = get_folder_path(FOLDERID.ProgramFilesX86)[0]
    VSCODE_SUBDIR = 'win32'
    VSCODE_INST_EXT = 'exe'
    if is_py_64bit:
        VSCODE_SUBDIR = 'win32-x64'
        _fallback = os.path.join(_windrive, 'Program Files')
        PROGRAM_FILES = get_folder_path(FOLDERID.ProgramFilesX64)[0]
    if PROGRAM_FILES is None:
        PROGRAM_FILES = os.environ.get('ProgramFiles', _fallback)
    VSCODE_INST_DIR = os.path.join(PROGRAM_FILES, 'Microsoft VS Code')
    VSCODE_EXE = os.path.join(VSCODE_INST_DIR, 'bin', 'code')
    CMD_REQ_SHELL = True
Exemplo n.º 51
0
    def title(self):

        length = windll.user32.GetWindowTextLengthW(self.hwnd) + 1
        title = create_unicode_buffer(length)
        windll.user32.GetWindowTextW(self.hwnd, title, length)
        return wstring_at(title)
Exemplo n.º 52
0
to_name = defaultdict(list)
from_name = defaultdict(list)
scan_code_to_vk = {}

distinct_modifiers = [
    (),
    ('shift', ),
    ('alt gr', ),
    ('num lock', ),
    ('shift', 'num lock'),
    ('caps lock', ),
    ('shift', 'caps lock'),
    ('alt gr', 'num lock'),
]

name_buffer = ctypes.create_unicode_buffer(32)
unicode_buffer = ctypes.create_unicode_buffer(32)
keyboard_state = keyboard_state_type()


def get_event_names(scan_code, vk, is_extended, modifiers):
    is_keypad = (scan_code, vk, is_extended) in keypad_keys
    is_official = vk in official_virtual_keys
    if is_keypad and is_official:
        yield official_virtual_keys[vk][0]

    keyboard_state[0x10] = 0x80 * ('shift' in modifiers)
    keyboard_state[0x11] = 0x80 * ('alt gr' in modifiers)
    keyboard_state[0x12] = 0x80 * ('alt gr' in modifiers)
    keyboard_state[0x14] = 0x01 * ('caps lock' in modifiers)
    keyboard_state[0x90] = 0x01 * ('num lock' in modifiers)
 def GetClassName(hwnd):
     buff = ctypes.create_unicode_buffer(100)
     ctypes.windll.user32.GetClassNameW(hwnd, buff, 99)
     return buff.value
Exemplo n.º 54
0
def _win_create_ca_bundle(settings, destination):
    debug = settings.get('debug')

    certs = []

    now = datetime.datetime.utcnow()

    for store in [u"ROOT", u"CA"]:
        store_handle = crypt32.CertOpenSystemStoreW(None, store)

        if not store_handle:
            console_write(
                u'''
                Error opening system certificate store %s: %s
                ''',
                (store, extract_error())
            )
            continue

        cert_pointer = crypt32.CertEnumCertificatesInStore(store_handle, None)
        while bool(cert_pointer):
            context = cert_pointer.contents

            skip = False

            if context.dwCertEncodingType != X509_ASN_ENCODING:
                skip = True
                if debug:
                    console_write(
                        u'''
                        Skipping certificate since it is not x509 encoded
                        '''
                    )

            if not skip:
                cert_info = context.pCertInfo.contents

                subject_struct = cert_info.Subject

                subject_length = subject_struct.cbData
                subject_bytes = ctypes.create_string_buffer(subject_length)
                ctypes.memmove(ctypes.addressof(subject_bytes), subject_struct.pbData, subject_length)

                subject = parse_subject(subject_bytes.raw[:subject_length])

                name = None
                if 'commonName' in subject:
                    name = subject['commonName']
                if not name and 'organizationalUnitName' in subject:
                    name = subject['organizationalUnitName']

                # On Windows, only the last of a key is used
                if isinstance(name, list):
                    name = name[-1]

                not_before = convert_filetime_to_datetime(cert_info.NotBefore)
                not_after  = convert_filetime_to_datetime(cert_info.NotAfter)

                if not_before > now:
                    if debug:
                        console_write(
                            u'''
                            Skipping certificate "%s" since it is not valid yet
                            ''',
                            name
                        )
                    skip = True

            if not skip:
                if not_after < now:
                    if debug:
                        console_write(
                            u'''
                            Skipping certificate "%s" since it is no longer valid
                            ''',
                            name
                        )
                    skip = True

            if not skip:
                cert_length = context.cbCertEncoded
                data = ctypes.create_string_buffer(cert_length)
                ctypes.memmove(ctypes.addressof(data), context.pbCertEncoded, cert_length)

                details = parse(data.raw[:cert_length])
                if details['algorithm'] in ['md5WithRSAEncryption', 'md2WithRSAEncryption']:
                    if debug:
                        console_write(
                            u'''
                            Skipping certificate "%s" since it uses the
                            signature algorithm %s
                            ''',
                            (name, details['algorithm'])
                        )
                    skip = True

            if not skip:
                output_size = wintypes.DWORD()

                result = crypt32.CryptBinaryToStringW(ctypes.cast(data, PByte), cert_length,
                    CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, None,
                    ctypes.byref(output_size))
                length = output_size.value

                if not result:
                    console_write(
                        u'''
                        Error determining certificate size for "%s"
                        ''',
                        name
                    )
                    skip = True

            if not skip:
                buffer = ctypes.create_unicode_buffer(length)
                output_size = wintypes.DWORD(length)

                result = crypt32.CryptBinaryToStringW(ctypes.cast(data, PByte), cert_length,
                    CRYPT_STRING_BASE64HEADER | CRYPT_STRING_NOCR, buffer,
                    ctypes.byref(output_size))
                output = buffer.value

                if debug:
                    console_write(
                        u'''
                        Exported certificate "%s"
                        ''',
                        name
                    )

                certs.append(output.strip())

            cert_pointer = crypt32.CertEnumCertificatesInStore(store_handle, cert_pointer)

        result = crypt32.CertCloseStore(store_handle, 0)
        store_handle = None
        if not result:
            console_write(
                u'''
                Error closing certificate store "%s"
                ''',
                store
            )

    with open_compat(destination, 'w') as f:
        f.write(u"\n".join(certs))
Exemplo n.º 55
0
def to_unicode_buffer(value):
    # type: (str) -> Union[ctypes._CData, ctypes._CArgObject]
    """Convert value to a unicode buffer using ctypes."""
    return ctypes.create_unicode_buffer(str(value))
Exemplo n.º 56
0
"""
# 多账户打新专用脚本,支持v4+版本
# myRegister暂时没用上。暂时只支持同花顺交易端
"""
# coding: utf-8
import time
import os
import subprocess
import ctypes

from puppet_v4 import Puppet, switch_combo
from autologon import autologon

api = ctypes.windll.user32
buff = ctypes.create_unicode_buffer(32)
team = set()


def find(keyword):
    """ 枚举所有已登录的交易端 """
    @ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, ctypes.c_wchar_p)
    def check(hwnd, keyword):
        """ 筛选 """
        if api.IsWindowVisible(hwnd)\
            and api.GetWindowTextW(hwnd, buff, 32) > 6 and keyword in buff.value:
            team.add(hwnd)
        return 1

    for i in range(10):
        api.EnumWindows(check, keyword)
        time.sleep(3)
Exemplo n.º 57
0
"""
directories_to_remap = {}
directories_to_exclude = {}

user_path = os.path.expanduser("~")
if app.platform == "windows":
    is_windows = True
    import ctypes

    GetUserNameEx = ctypes.windll.secur32.GetUserNameExW
    NameDisplay = 3

    size = ctypes.pointer(ctypes.c_ulong(0))
    GetUserNameEx(NameDisplay, None, size)

    nameBuffer = ctypes.create_unicode_buffer(size.contents.value)
    GetUserNameEx(NameDisplay, nameBuffer, size)
    one_drive_path = os.path.expanduser(os.path.join("~", "OneDrive"))

    # this is probably not the correct way to check for onedrive, quick and dirty
    if os.path.isdir(os.path.expanduser(os.path.join("~",
                                                     r"OneDrive\Desktop"))):
        default_folder = os.path.join("~", "Desktop")

        directories_to_remap = {
            "Desktop": os.path.join(one_drive_path, "Desktop"),
            "Documents": os.path.join(one_drive_path, "Documents"),
            "Downloads": os.path.join(user_path, "Downloads"),
            "Music": os.path.join(user_path, "Music"),
            "OneDrive": one_drive_path,
            "Pictures": os.path.join(one_drive_path, "Pictures"),
Exemplo n.º 58
0
    OBJECTS = 3

    NUM = 4  # number of layers


## PATHS
# workaround, so it can be used to create paths within PATHS
if 'UH_USER_DIR' in os.environ:
    # Prefer the value from the environment. Used to override user dir when
    # running GUI tests.
    _user_dir = unicode(os.environ['UH_USER_DIR'], encoding='utf-8')
elif platform.system() != "Windows":
    _user_dir = os.path.join(os.path.expanduser('~'), '.unknown-horizons')
else:
    import ctypes.wintypes
    buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
    # get the My Documents folder into buf.value
    ctypes.windll.shell32.SHGetFolderPathW(0, 5, 0, 0, buf)
    my_games = os.path.join(buf.value, 'My Games')
    if not os.path.exists(my_games):
        os.makedirs(my_games)
    _user_dir = os.path.join(my_games, 'unknown-horizons')


class GFX:
    BUILDING_OUTLINE_THRESHOLD = 96
    BUILDING_OUTLINE_WIDTH = 2

    UNIT_OUTLINE_THRESHOLD = 96
    UNIT_OUTLINE_WIDTH = 2
Exemplo n.º 59
0
def get_vlc():
    """
    In order to make this module more testable, we have to wrap the VLC import inside a method. We do this so that we
    can mock out the VLC module entirely.

    :return: The "vlc" module, or None
    """
    if 'openlp.core.ui.media.vendor.vlc' in sys.modules:
        # If VLC has already been imported, no need to do all the stuff below again
        is_vlc_available = False
        try:
            is_vlc_available = bool(
                sys.modules['openlp.core.ui.media.vendor.vlc'].
                get_default_instance())
        except:
            pass
        if is_vlc_available:
            return sys.modules['openlp.core.ui.media.vendor.vlc']
        else:
            return None
    is_vlc_available = False
    try:
        if is_macosx():
            # Newer versions of VLC on OS X need this. See https://forum.videolan.org/viewtopic.php?t=124521
            os.environ[
                'VLC_PLUGIN_PATH'] = '/Applications/VLC.app/Contents/MacOS/plugins'
        # On Windows when frozen in PyInstaller, we need to blank SetDllDirectoryW to allow loading of the VLC dll.
        # This is due to limitations (by desgin) in PyInstaller. SetDllDirectoryW original value is restored once
        # VLC has been imported.
        if is_win():
            buffer_size = 1024
            dll_directory = ctypes.create_unicode_buffer(buffer_size)
            new_buffer_size = ctypes.windll.kernel32.GetDllDirectoryW(
                buffer_size, dll_directory)
            dll_directory = ''.join(dll_directory[:new_buffer_size]).replace(
                '\0', '')
            log.debug('Original DllDirectory: %s' % dll_directory)
            ctypes.windll.kernel32.SetDllDirectoryW(None)
        from openlp.core.ui.media.vendor import vlc
        if is_win():
            ctypes.windll.kernel32.SetDllDirectoryW(dll_directory)
        is_vlc_available = bool(vlc.get_default_instance())
    except (ImportError, NameError, NotImplementedError):
        pass
    except OSError as e:
        # this will get raised the first time
        if is_win():
            if not isinstance(e, WindowsError) and e.winerror != 126:
                raise
        else:
            pass
    if is_vlc_available:
        try:
            VERSION = vlc.libvlc_get_version().decode('UTF-8')
        except:
            VERSION = '0.0.0'
        # LooseVersion does not work when a string contains letter and digits (e. g. 2.0.5 Twoflower).
        # http://bugs.python.org/issue14894
        if LooseVersion(VERSION.split()[0]) < LooseVersion('1.1.0'):
            is_vlc_available = False
            log.debug(
                'VLC could not be loaded, because the vlc version is too old: %s'
                % VERSION)
    if is_vlc_available:
        return vlc
    else:
        return None
def get_ctype_string_buffer(size):
    if sys.platform == 'win32':
        return ctypes.create_unicode_buffer(size)
    else:
        return ctypes.create_string_buffer(size)