Ejemplo n.º 1
0
def destroyHighlightWin():
    global wndclass
    global hwndHide
    for i in xrange(4):
        windll.user32.DestroyWindow(focusHwndList[i])
    windll.user32.DestroyWindow(hwndHide)
    while True:
        ret = windll.user32.UnregisterClassA(wndclass.lpszClassName,
                                             wndclass.hInstance)
        if ret == 0:
            if GetLastError() == ERROR_CLASS_HAS_WINDOWS:
                time.sleep(0.5)
            else:
                log.error(FormatError())
                break
        else:
            break
    wndclass = None
    hwndHide = None
def _create_symlink(source, link_name, dwFlags):
    # Note: Win32 documentation for CreateSymbolicLink is incorrect.
    # On success, the function returns "1".
    # On error, the function returns some random value (e.g. 1280).
    # The best bet seems to use "GetLastError" and check for error/success.
    CreateSymbolicLinkW(link_name, source,
                        dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)
    code = get_last_error()
    if code != ERROR_SUCCESS:
        # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
        # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
        # retry without it."
        CreateSymbolicLinkW(link_name, source, dwFlags)
        code = get_last_error()
        if code != ERROR_SUCCESS:
            error_desc = FormatError(code).strip()
            if code == ERROR_PRIVILEGE_NOT_HELD:
                raise OSError(errno.EPERM, error_desc, link_name)
            _raise_winerror(
                code, 'Error creating symbolic link \"%s\"'.format(link_name))
def send2trash(paths):
    if not isinstance(paths, list):
        paths = [paths]
    # convert data type
    paths = [
        text_type(path, "mbcs") if not isinstance(path, text_type) else path
        for path in paths
    ]
    # convert to full paths
    paths = [
        op.abspath(path) if not op.isabs(path) else path for path in paths
    ]
    # get short path to handle path length issues
    paths = [get_short_path_name(path) for path in paths]
    # convert to a single string of null terminated paths
    paths = "\0".join(paths)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    # FIX: https://github.com/hsoft/send2trash/issues/17
    # Starting in python 3.6.3 it is no longer possible to use:
    # LPCWSTR(path + '\0') directly as embedded null characters are no longer
    # allowed in strings
    # Workaround
    #  - create buffer of c_wchar[] (LPCWSTR is based on this type)
    #  - buffer is two c_wchar characters longer (double null terminator)
    #  - cast the address of the buffer to a LPCWSTR
    # NOTE: based on how python allocates memory for these types they should
    # always be zero, if this is ever not true we can go back to explicitly
    # setting the last two characters to null using buffer[index] = '\0'.
    buffer = create_unicode_buffer(paths, len(paths) + 2)
    fileop.pFrom = LPCWSTR(addressof(buffer))
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(result, FormatError(result), paths)
Ejemplo n.º 4
0
 def get_text():
     data_handle = GetClipboardData(win32con.CF_UNICODETEXT)
     if not data_handle:
         errback("no data handle")
         return
     data = GlobalLock(data_handle)
     if not data:
         errback("failed to lock handle")
         return
     try:
         wstr = cast(data, LPCWSTR)
         ulen = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, None, 0, None,
                                    None)
         if ulen > MAX_CLIPBOARD_PACKET_SIZE:
             errback("too much data")
             return
         buf = create_string_buffer(ulen)
         l = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, byref(buf), ulen,
                                 None, None)
         if l > 0:
             if buf.raw[l - 1:l] == b"\0":
                 s = buf.raw[:l - 1]
             else:
                 s = buf.raw[:l]
             if CONVERT_LINE_ENDINGS:
                 v = s.decode("utf8").replace("\r\n",
                                              "\n").encode("utf8")
             else:
                 v = strtobytes(s)
             log("got %i bytes of data: %s", len(s),
                 repr_ellipsized(str(s)))
             callback(v)
         else:
             errback("failed to convert to UTF8: %s" %
                     FormatError(get_last_error()))
     finally:
         GlobalUnlock(data)
Ejemplo n.º 5
0
 def StartYardServer(self):
     try:
         rkey = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Webers\\Y.A.R.D")
         path = RegQueryValueEx(rkey, "program")[0]
         if not os.path.exists(path):
             raise Exception
     except:
         raise self.Exception(
             "Please start Yards.exe first and configure it."
         )
     try:
         hProcess = CreateProcess(
             None,
             path,
             None,
             None,
             0,
             CREATE_NEW_CONSOLE,
             None,
             None,
             STARTUPINFO()
         )[0]
     except Exception, exc:
         raise eg.Exception(FormatError(exc[0]))
Ejemplo n.º 6
0
def _raise_winerror(code, error_desc):
    win_error_desc = FormatError(code).strip()
    error_desc = "%s: %s".format(error_desc, win_error_desc)
    raise WinError(code, error_desc)
Ejemplo n.º 7
0
 def _enhkey_error(self):
     err = get_last_error()
     if err == CRYPT_E_NOT_FOUND:
         return True
     errmsg = FormatError(err)
     raise OSError(err, errmsg)
Ejemplo n.º 8
0
def assert_success(success):
    if not success:
        raise AssertionError(FormatError())
Ejemplo n.º 9
0
 def extract_error():
     error_num = GetLastError()
     error_string = FormatError(error_num)
     return unicode_from_os(error_string)
Ejemplo n.º 10
0
 def get_text():
     formats = []
     fmt = 0
     while True:
         fmt = EnumClipboardFormats(fmt)
         if fmt:
             formats.append(fmt)
         else:
             break
     log("clipboard formats: %s", csv(format_name(x) for x in formats))
     matching = []
     for u in (utf8, not utf8):
         if u:
             fmts = [win32con.CF_UNICODETEXT]
         else:
             fmts = [win32con.CF_TEXT, win32con.CF_OEMTEXT]
         matching += [fmt for fmt in formats if fmt in fmts]
     log("supported formats: %s (prefer utf8: %s)",
         csv(format_name(x) for x in matching), utf8)
     if not matching:
         log("no supported formats, only: %s",
             csv(format_name(x) for x in formats))
         errback()
         return True
     data_handle = None
     for fmt in matching:
         data_handle = GetClipboardData(fmt)
         log("GetClipboardData(%s)=%#x", format_name(fmt), data_handle
             or 0)
         if data_handle:
             break
     if not data_handle:
         log("no valid data handle using %s (may try again)",
             csv(format_name(x) for x in matching))
         return False
     data = GlobalLock(data_handle)
     if not data:
         log("failed to lock data handle %#x (may try again)",
             data_handle)
         return False
     log("got data handle lock %#x for format '%s'", data,
         format_name(fmt))
     try:
         if fmt == win32con.CF_UNICODETEXT:
             wstr = cast(data, LPCWSTR)
             ulen = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, None, 0,
                                        None, None)
             if ulen > MAX_CLIPBOARD_PACKET_SIZE:
                 errback("unicode data is too large: %i bytes" % ulen)
                 return True
             buf = create_string_buffer(ulen)
             l = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, byref(buf),
                                     ulen, None, None)
             if l == 0:
                 errback("failed to convert to UTF8: %s" %
                         FormatError(get_last_error()))
                 return True
             if buf.raw[l - 1:l] == b"\0":
                 s = buf.raw[:l - 1]
             else:
                 s = buf.raw[:l]
             log("got %i bytes of UNICODE data: %s", len(s),
                 ellipsizer(s))
             if CONVERT_LINE_ENDINGS:
                 v = s.decode("utf8").replace("\r\n",
                                              "\n").encode("utf8")
             else:
                 v = strtobytes(s)
             callback(v)
             return True
         #CF_TEXT or CF_OEMTEXT:
         astr = cast(data, LPCSTR)
         s = astr.value.decode("latin1")
         if CONVERT_LINE_ENDINGS:
             s = s.replace("\r\n", "\n")
         b = s.encode("latin1")
         ulen = len(b)
         if ulen > MAX_CLIPBOARD_PACKET_SIZE:
             errback("text data is too large: %i characters" % ulen)
             return True
         log("got %i bytes of TEXT data: %s", len(b), ellipsizer(b))
         callback(b)
         return True
     finally:
         GlobalUnlock(data)
Ejemplo n.º 11
0
 def format_err(err=None):
     if err is None:
         err = get_last_error()
     #return str(WinError(err))
     return "[Error %i] %s" % (err, FormatError(err))
Ejemplo n.º 12
0
def _start_scanning():
    '''
    Private method for scanning and returns the available devices.
    '''
    global available  # pylint: disable=global-statement
    global wireless_interfaces  # pylint: disable=global-statement
    NegotiatedVersion = DWORD()
    ClientHandle = HANDLE()

    wlan = WlanOpenHandle(1, None, byref(NegotiatedVersion),
                          byref(ClientHandle))

    if wlan:
        sys_exit(FormatError(wlan))

    # find all wireless network interfaces
    pInterfaceList = pointer(WLAN_INTERFACE_INFO_LIST())
    wlan = WlanEnumInterfaces(ClientHandle, None, byref(pInterfaceList))
    if wlan:
        sys_exit(FormatError(wlan))

    result = None
    try:
        ifaces = customresize(pInterfaceList.contents.InterfaceInfo,
                              pInterfaceList.contents.NumberOfItems)

        # find each available network for each interface
        wireless_interfaces = ifaces
        for iface in ifaces:
            pAvailableNetworkList = pointer(WLAN_AVAILABLE_NETWORK_LIST())
            wlan = WlanGetAvailableNetworkList(ClientHandle,
                                               byref(iface.InterfaceGuid), 0,
                                               None,
                                               byref(pAvailableNetworkList))

            if wlan:
                sys_exit(FormatError(wlan))

            try:
                avail_net_list = pAvailableNetworkList.contents
                networks = customresize(avail_net_list.Network,
                                        avail_net_list.NumberOfItems)

                # Assigning the value of networks to the global variable
                # `available`, so it could be used in other methods.
                available = networks
                _make_dict()
                wlan = WlanDisconnect(ClientHandle, byref(iface.InterfaceGuid),
                                      None)

                if wlan:
                    sys_exit(FormatError(wlan))
                WlanCloseHandle(ClientHandle, None)

            finally:
                WlanFreeMemory(pAvailableNetworkList)

    finally:
        WlanFreeMemory(pInterfaceList)
        result = get_available_wifi()

    return result
Ejemplo n.º 13
0
def last_error():
    """
    Returns the last error as reported by the OS.
    """
    err = get_last_error()
    return "0x%08X: %s" % (err, FormatError(err))
Ejemplo n.º 14
0
 def __init__(self, errno):
     from ctypes import FormatError
     self.winerror = errno
     self.strerror = FormatError(errno)
Ejemplo n.º 15
0
def initialize_gcrypt(required_ver):
    from ctypes import c_void_p
    from gnutls.library._init import gcrypt_thread_callbacks_ptr

    GCRYCTL_INIT_SECMEM = 24
    GCRYCTL_SUSPEND_SECMEM_WARN = 28
    GCRYCTL_RESUME_SECMEM_WARN = 29
    GCRYCTL_DISABLE_SECMEM = 37
    GCRYCTL_SET_THREAD_CBS = 47
    GCRYCTL_INITIALIZATION_FINISHED = 38

    system = get_system_name()

    if system == 'windows':
        from ctypes import CDLL, FormatError, POINTER, byref, create_unicode_buffer, c_wchar_p, sizeof, windll
        from ctypes.wintypes import BOOL, DWORD, HANDLE, HMODULE

        GetCurrentProcess = windll.kernel32.GetCurrentProcess
        GetCurrentProcess.argtypes = []
        GetCurrentProcess.restype = HANDLE

        try:
            EnumProcessModules = windll.kernel32.EnumProcessModules
        except AttributeError:
            EnumProcessModules = windll.psapi.EnumProcessModules
        EnumProcessModules.argtypes = [
            HANDLE, POINTER(HMODULE), DWORD,
            POINTER(DWORD)
        ]
        EnumProcessModules.restype = BOOL

        GetModuleFileName = windll.kernel32.GetModuleFileNameW
        GetModuleFileName.argtypes = [HMODULE, c_wchar_p, DWORD]
        GetModuleFileName.restype = DWORD

        module_handles = (HMODULE * 1024)()
        module_name = create_unicode_buffer(65536)
        needed = DWORD()

        if EnumProcessModules(GetCurrentProcess(), module_handles,
                              sizeof(module_handles), byref(needed)):
            for i in xrange(needed.value / sizeof(HMODULE)):
                if GetModuleFileName(
                        module_handles[i], module_name,
                        len(module_name)) and 'libgcrypt' in module_name.value:
                    libgcrypt = CDLL(module_name.value)
                    break
            else:
                raise RuntimeError(
                    'cannot find libgcrypt among the loaded dlls')
        else:
            raise RuntimeError('cannot obtain the process modules: %s' %
                               FormatError())
        gcry_control = libgcrypt.gcry_control
        gcry_check_version = libgcrypt.gcry_check_version
    elif system == 'cygwin':
        libgcrypt = load_library(name='gcrypt', version=11)
        gcry_control = libgcrypt.gcry_control
        gcry_check_version = libgcrypt.gcry_check_version
    else:
        gcry_control = libgnutls.gcry_control
        gcry_check_version = libgnutls.gcry_check_version

    gcry_control(GCRYCTL_SET_THREAD_CBS, c_void_p(gcrypt_thread_callbacks_ptr))
    if gcry_check_version(required_ver) is None:
        version = gcry_check_version(None)
        raise RuntimeError(
            "Found gcrypt library version %s, but at least version %s is required"
            % (version, required_ver))

    if system == 'cygwin':
        gcry_control(GCRYCTL_DISABLE_SECMEM, 0)
    else:
        gcry_control(GCRYCTL_SUSPEND_SECMEM_WARN)
        gcry_control(GCRYCTL_INIT_SECMEM, 32768, 0)
        gcry_control(GCRYCTL_RESUME_SECMEM_WARN)
    gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0)