コード例 #1
0
ファイル: winapi.py プロジェクト: ervandarnell/pywinusb
def get_device_path(h_info, interface_data, ptr_info_data = None):
    """"Returns Hardware device path
    Parameters:
        h_info,         interface set info handler
        interface_data, device interface enumeration data
        ptr_info_data,  pointer to SP_DEVINFO_DATA() instance to receive details
    """
    required_size = c_ulong(0)

    dev_inter_detail_data         = SP_DEVICE_INTERFACE_DETAIL_DATA()
    dev_inter_detail_data.cb_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)

    # get actual storage requirement
    SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data),
            None, 0, byref(required_size),
            None)
    ctypes.resize(dev_inter_detail_data, required_size.value)

    # read value
    SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data),
            byref(dev_inter_detail_data), required_size, None,
            ptr_info_data)

    # extract string only
    return dev_inter_detail_data.get_string()
コード例 #2
0
ファイル: test_io_stdlib.py プロジェクト: visemet/winnan
 def byteslike(*pos, **kw):
     """Create a bytes-like object having no string or sequence methods"""
     data = bytes(*pos, **kw)
     obj = EmptyStruct()
     ctypes.resize(obj, len(data))
     memoryview(obj).cast("B")[:] = data
     return obj
コード例 #3
0
ファイル: core.py プロジェクト: wolneykien/cx
    def recv(self):
        """
        Receive a request message from the client
        """
        msgdata = (c_ubyte * NORM_MSG_SIZE)()
        msg = mempair(p9msg, msgdata)
        (baddr, blen) = msg.databuf()
        l = libc.recv(self.__clsock, baddr, blen, 0)
        hdr = msg.car()
        if l > sizeof(hdr):
            if hdr.size > l:
                if hdr.size > MAX_MSG_SIZE:
                    raise IOError("The message is too large: %d bytes" %
                                  hdr.size)
                resize(msgdata, hdr.size)
                (baddr, blen) = msg.databuf()
                l2 = libc.recv(self.__clsock, baddr + hdr.size - l, blen - l,
                               0)
                if l2 > 0:
                    l += l2
                else:
                    raise IOError("Unable to read the %d remaining bytes" %
                                  blen - l)
        else:
            raise IOError("Unable to read the message")

        return (l, msg)
コード例 #4
0
ファイル: win.py プロジェクト: wujcheng/salt
 def _set_unicode_buffer(self, value):
     cls = type(self)
     wchar_size = ctypes.sizeof(WCHAR)
     bufsize = (len(value) + 1) * wchar_size
     ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
     addr = ctypes.addressof(self) + ctypes.sizeof(cls)
     ctypes.memmove(addr, value, bufsize)
コード例 #5
0
    def get_token_obj(self):
        token_addr = 0
        handle_info = SYSTEM_HANDLE_INFORMATION_EX()
        length = ctypes.c_ulong()

        while True:
            status = NtQuerySystemInformation(SystemHandleInformationEx,
                                              ctypes.byref(handle_info),
                                              ctypes.sizeof(handle_info),
                                              ctypes.byref(length))
            if status != STATUS_INFO_LENGTH_MISMATCH:
                break
            ctypes.resize(handle_info, length.value)

        if status < 0:
            raise WinErrorFromNtStatus(status)

        if status == 0:
            pid = GetCurrentProcessId()
            token = wintypes.HANDLE(0)
            curproc = wintypes.HANDLE(GetCurrentProcess())
            success = OpenProcessToken(curproc, TOKEN_ALL_ACCESS,
                                       ctypes.byref(token))

            if success:
                for i in range(handle_info.NumberOfHandles):
                    if pid == handle_info.Handles[i].UniqueProcessId:
                        h = handle_info.Handles[i]
                        if (token.value == h.Handle
                                or CompareObjectHandles(token, h.Handle)):
                            token_addr = h.Object
                            break
                CloseHandle(token)
        return token_addr
コード例 #6
0
 def __init__(self, connectKey , platforms):
     super(AS2PSConnectCommand,self).__init__(eCommand_Main_Connect,eCommand_Sub_Connect_Req)
     self.nConnectKey    = connectKey
     self.nPlatformCount = sizeof(platforms) / sizeof(TPlatformContext)
     if self.nPlatformCount > 0:
         resize(self,sizeof(self) + sizeof(TPlatformContext) * self.nPlatformCount)
         memmove(addressof(self) + sizeof(self.__class__),platforms,sizeof(platforms))
コード例 #7
0
    def list_usb_devices(self, **kwargs):
        self.device_paths = []
        value = 0x00000000
        try:
            if kwargs["default"] == True:
                value |= DIGCF_DEFAULT
            if kwargs["present"] == True:
                value |= DIGCF_PRESENT
            if kwargs["allclasses"] == True:
                value |= DIGCF_ALLCLASSES
            if kwargs["profile"] == True:
                value |= DIGCF_PROFILE
            if kwargs["deviceinterface"] == True:
                value |= DIGCF_DEVICE_INTERFACE
        except KeyError:
            if value == 0x00000000:
                value = 0x00000010
            pass

        flags = DWORD(value)
        self.handle = self.api.exec_function_setupapi(SetupDiGetClassDevs,
                                                      byref(self.guid), None,
                                                      None, flags)

        sp_device_interface_data = SpDeviceInterfaceData()
        sp_device_interface_data.cb_size = sizeof(sp_device_interface_data)
        sp_device_interface_detail_data = SpDeviceInterfaceDetailData()
        sp_device_info_data = SpDevinfoData()
        sp_device_info_data.cb_size = sizeof(sp_device_info_data)
        i = 0
        required_size = c_ulong(0)
        member_index = DWORD(i)

        while self.api.exec_function_setupapi(SetupDiEnumDeviceInterfaces,
                                              self.handle, None,
                                              byref(self.guid), member_index,
                                              byref(sp_device_interface_data)):
            self.api.exec_function_setupapi(SetupDiGetDeviceInterfaceDetail,
                                            self.handle,
                                            byref(sp_device_interface_data),
                                            None, 0, byref(required_size),
                                            None)
            resize(sp_device_interface_detail_data, required_size.value)
            sp_device_interface_detail_data.cb_size = sizeof(
                SpDeviceInterfaceDetailData) - sizeof(WCHAR * 1)
            if self.api.exec_function_setupapi(
                    SetupDiGetDeviceInterfaceDetail, self.handle,
                    byref(sp_device_interface_data),
                    byref(sp_device_interface_detail_data), required_size,
                    byref(required_size), byref(sp_device_info_data)):
                path = wstring_at(
                    byref(sp_device_interface_detail_data, sizeof(DWORD)))
                self.device_paths.append(path)
            i += 1
            member_index = DWORD(i)
            required_size = c_ulong(0)
            resize(sp_device_interface_detail_data,
                   sizeof(SpDeviceInterfaceDetailData))
        return len(self.device_paths) > 0
コード例 #8
0
ファイル: Functions.py プロジェクト: Starlon/LCD4Py
def resizeArray(array, new_size):
	resize(array, sizeof(array._type_)*new_size)
	newarray = (array._type_*new_size).from_address(addressof(array))
	if hasattr(array,"original"):
		newarray.original = array.original
	else:
		newarray.original = array
	return newarray
コード例 #9
0
ファイル: testclient.py プロジェクト: ltbj/thunderhill-racing
def copyImage(byte_array, imageSize):
    if imageSize > 8:
        ctypes.resize(byte_array, imageSize)
        image = []
        for i in range(imageSize):
            image.append(byte_array[i])
        return array.array('B', image).tostring()
    return byte_array
コード例 #10
0
    def len(self, value):
        rsize = self._extra_end + value
        if ctypes.sizeof(self) < rsize:
            try:
                ctypes.resize(self, rsize)
            except ValueError:
                raise ValueError("Need %s more space" % (rsize - ctypes.sizeof(self)))

        self._len = self._extra_size + value
コード例 #11
0
ファイル: utils.py プロジェクト: CIbeaST/udlg_advance_i18n
def resize_array(array, size):
    """
    extends array with given size

    :param array: ctypes array
    :param int size: new size (should be more than current size)
    :return: pointer on new array
    """
    resize(array, sizeof(array._type_) * size)
    return (array._type_ * size).from_address(addressof(array))
コード例 #12
0
ファイル: win.py プロジェクト: umutbb/hubble
 def _set_unicode_buffer(self, values):
     cls = type(self)
     wchar_size = ctypes.sizeof(WCHAR)
     bufsize = (len('\x00'.join(values)) + 1) * wchar_size
     ctypes.resize(self, ctypes.sizeof(cls) + bufsize)
     addr = ctypes.addressof(self) + ctypes.sizeof(cls)
     for value in values:
         bufsize = (len(value) + 1) * wchar_size
         ctypes.memmove(addr, value, bufsize)
         addr += bufsize
コード例 #13
0
    def len(self, value):
        rsize = self._extra_end + value
        if ctypes.sizeof(self) < rsize:
            try:
                ctypes.resize(self, rsize)
            except ValueError:
                raise ValueError("Need %s more space" %
                                 (rsize - ctypes.sizeof(self)))

        self._len = self._extra_size + value
コード例 #14
0
ファイル: efi.py プロジェクト: kirkboy/bits
 def _get_info(self, information_type_guid, info):
     self._check_closed()
     guid = GUID(information_type_guid)
     size = ctypes.c_ulong()
     status = call(self.file_protocol.GetInfo, ctypes.addressof(self.file_protocol), ctypes.addressof(guid), ctypes.addressof(size), 0)
     if status != EFI_BUFFER_TOO_SMALL:
         check_status(status)
     ctypes.resize(info, size.value)
     check_status(call(self.file_protocol.GetInfo, ctypes.addressof(self.file_protocol), ctypes.addressof(guid), ctypes.addressof(size), ctypes.addressof(info)))
     return info
コード例 #15
0
ファイル: core.py プロジェクト: msimon00/obspy
    def __init__(self, trace, data, dataquality):
        """
        The init function requires a ObsPy Trace object which will be used to
        fill self.mstg.
        """
        # Initialize MSTraceGroup
        mstg = clibmseed.mst_initgroup(None)
        self.mstg = mstg
        # Set numtraces.
        mstg.contents.numtraces = 1
        # Initialize MSTrace object and connect with group
        mstg.contents.traces = clibmseed.mst_init(None)
        chain = mstg.contents.traces

        # Figure out the datatypes.
        sampletype = SAMPLETYPE[data.dtype.type]
        c_dtype = DATATYPES[sampletype]

        # Set the header values.
        chain.contents.network = trace.stats.network
        chain.contents.station = trace.stats.station
        chain.contents.location = trace.stats.location
        chain.contents.channel = trace.stats.channel
        chain.contents.dataquality = dataquality
        chain.contents.type = '\x00'
        chain.contents.starttime = \
                util._convertDatetimeToMSTime(trace.stats.starttime)
        chain.contents.endtime = \
                util._convertDatetimeToMSTime(trace.stats.endtime)
        chain.contents.samprate = trace.stats.sampling_rate
        chain.contents.samplecnt = trace.stats.npts
        chain.contents.numsamples = trace.stats.npts
        chain.contents.sampletype = sampletype

        # Create a single datapoint and resize its memory to be able to
        # hold all datapoints.
        tempdatpoint = c_dtype()
        datasize = SAMPLESIZES[sampletype] * trace.stats.npts
        # XXX: Ugly workaround for traces with less than 17 data points
        if datasize < 17:
            datasize = 17
        C.resize(tempdatpoint, datasize)
        # The datapoints in the MSTG structure are a pointer to the memory
        # area reserved for tempdatpoint.
        chain.contents.datasamples = C.cast(C.pointer(tempdatpoint),
                                            C.c_void_p)
        # Swap if wrong byte order because libmseed expects native byteorder.
        if data.dtype.byteorder != "=":
            data = data.byteswap()
        # Pointer to the NumPy data buffer.
        datptr = data.ctypes.get_data()
        # Manually move the contents of the NumPy data buffer to the
        # address of the previously created memory area.
        C.memmove(chain.contents.datasamples, datptr, datasize)
コード例 #16
0
ファイル: core.py プロジェクト: David-777/obspy
    def __init__(self, trace, data, dataquality):
        """
        The init function requires a ObsPy Trace object which will be used to
        fill self.mstg.
        """
        # Initialize MSTraceGroup
        mstg = clibmseed.mst_initgroup(None)
        self.mstg = mstg
        # Set numtraces.
        mstg.contents.numtraces = 1
        # Initialize MSTrace object and connect with group
        mstg.contents.traces = clibmseed.mst_init(None)
        chain = mstg.contents.traces

        # Figure out the datatypes.
        sampletype = SAMPLETYPE[data.dtype.type]
        c_dtype = DATATYPES[sampletype]

        # Set the header values.
        chain.contents.network = trace.stats.network
        chain.contents.station = trace.stats.station
        chain.contents.location = trace.stats.location
        chain.contents.channel = trace.stats.channel
        chain.contents.dataquality = dataquality
        chain.contents.type = '\x00'
        chain.contents.starttime = \
                util._convertDatetimeToMSTime(trace.stats.starttime)
        chain.contents.endtime = \
                util._convertDatetimeToMSTime(trace.stats.endtime)
        chain.contents.samprate = trace.stats.sampling_rate
        chain.contents.samplecnt = trace.stats.npts
        chain.contents.numsamples = trace.stats.npts
        chain.contents.sampletype = sampletype

        # Create a single datapoint and resize its memory to be able to
        # hold all datapoints.
        tempdatpoint = c_dtype()
        datasize = SAMPLESIZES[sampletype] * trace.stats.npts
        # XXX: Ugly workaround for traces with less than 17 data points
        if datasize < 17:
            datasize = 17
        C.resize(tempdatpoint, datasize)
        # The datapoints in the MSTG structure are a pointer to the memory
        # area reserved for tempdatpoint.
        chain.contents.datasamples = C.cast(C.pointer(tempdatpoint),
                                            C.c_void_p)
        # Swap if wrong byte order because libmseed expects native byteorder.
        if data.dtype.byteorder != "=":
            data = data.byteswap()
        # Pointer to the NumPy data buffer.
        datptr = data.ctypes.get_data()
        # Manually move the contents of the NumPy data buffer to the
        # address of the previously created memory area.
        C.memmove(chain.contents.datasamples, datptr, datasize)
コード例 #17
0
    def save(self, fn):
        """
        Serializes the dictionary to file [fn].

        Args:
            fn: The filename of the file.
        """
        resize(self._data, self._header.n_nodes * sizeof(Node))
        fp = open(fn, "wb")
        fp.write(self._header)
        fp.write(self._data)
        fp.close()
コード例 #18
0
ファイル: win.py プロジェクト: umutbb/hubble
 def from_address_copy(cls, address, size=None):
     x = ctypes.Structure.__new__(cls)
     if size is not None:
         ctypes.resize(x, size)
     ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x))
     delta = ctypes.addressof(x) - address
     for n in cls._string_names_:
         ustr = getattr(x, '_{}'.format(n))
         addr = ctypes.c_void_p.from_buffer(ustr.Buffer)
         if addr:
             addr.value += delta
     return x
コード例 #19
0
def get_handles():
    info = SYSTEM_HANDLE_INFORMATION_EX()
    length = wintypes.ULONG()
    while True:
        status = ntdll.NtQuerySystemInformation(
            SystemExtendedHandleInformation, ctypes.byref(info),
            ctypes.sizeof(info), ctypes.byref(length))
        if status != STATUS_INFO_LENGTH_MISMATCH:
            break
        ctypes.resize(info, length.value)
    if status < 0:
        raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status))
    return info.Handles
コード例 #20
0
 def create_notification_struct(self, payload):
     # type: (bytes) -> structs.SAdsNotificationHeader
     buf = b"\x00" * 12  # hNotification, nTimeStamp
     buf += struct.pack("<i", len(payload))
     buf += payload
     notification = structs.SAdsNotificationHeader()
     resize(notification, len(buf))
     memmove(
         pointer(notification),
         (ctypes.c_ubyte * len(buf)).from_buffer_copy(buf),
         sizeof(notification),
     )
     return notification
コード例 #21
0
ファイル: efi.py プロジェクト: kirkboy/bits
def get_variable(name, guid):
    attribute = ctypes.c_uint32(0)
    data = ctypes.create_string_buffer(1)
    size = ctypes.c_ulong(ctypes.sizeof(data))
    while True:
        status = call(system_table.RuntimeServices.contents.GetVariable, ctypes.addressof(name), ctypes.addressof(guid), ctypes.addressof(attribute), ctypes.addressof(size), ctypes.addressof(data))
        if status == EFI_NOT_FOUND:
            break
        if status == EFI_BUFFER_TOO_SMALL:
            ctypes.resize(data, size.value)
            continue
        check_status(status)
        return data, attribute.value, size.value
コード例 #22
0
ファイル: efi.py プロジェクト: kirkboy/bits
 def read(self, size=-1):
     self._check_closed()
     if size < 0:
         try:
             size = self.file_info.FileSize - self.tell()
         except EFIException as e:
             size = self.file_info.FileSize
     size = ctypes.c_ulong(size)
     buf = ctypes.create_string_buffer(0)
     ctypes.resize(buf, size.value)
     check_status(call(self.file_protocol.Read, ctypes.addressof(self.file_protocol), ctypes.addressof(size), ctypes.addressof(buf)))
     if size.value != ctypes.sizeof(buf):
         ctypes.resize(buf, size.value)
     return buf.raw
コード例 #23
0
ファイル: blueforsValves.py プロジェクト: hgrollnt/pyHegel
 def get_all_dev_interface(ClassGuid,
                           Enumerator,
                           Flags,
                           search_interface=GUID_INTERFACE_USB_DEVICE):
     if not Flags & DIGCF_DEVICEINTERFACE:
         raise ValueError, "The DIGCF_DEVICEINTERFACE flag is required here."
     devinfo = GetClassDevs(ClassGuid, Enumerator, 0, Flags)
     if devinfo == INVALID_HANDLE_VALUE:
         raise RuntimeError, format_err()
     m = 0
     dinter = SP_DEVICE_INTERFACE_DATA()
     dinter.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA)
     bufsize = DWORD()
     res = []
     while True:
         if not EnumDeviceInterfaces(devinfo, None, search_interface, m,
                                     dinter):
             err = get_last_error()
             if err != ERROR_NO_MORE_ITEMS:
                 DestroyDeviceInfoList(devinfo)
                 raise RuntimeError, 'EnumDeviceInterface ' + format_err(
                     err)
             break
         # Find required bufsize
         GetDeviceInterfaceDetail(devinfo, dinter, None, 0, bufsize, None)
         if USE_RESIZE:
             detail = SP_DEVICE_INTERFACE_DETAIL_DATA()
             resize(detail, bufsize.value)
             detailp = byref(detail)
         else:
             detail = detail_gen(bufsize.value)
             # cast is needed because GetDeviceInterfaceDetail is defined to require
             #  POINTER(SP_DEVICE_INTERFACE_DETAIL_DATA)
             # Instead of a cast the object could also be a subclass
             detailp = cast(pointer(detail),
                            POINTER(SP_DEVICE_INTERFACE_DETAIL_DATA))
         detail.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)
         # Note that the last argument could be used to have the SP_DEVINFO_DATA
         # reference of this entry that can be used with GetDeviceInstanceId
         if not GetDeviceInterfaceDetail(devinfo, dinter, detailp,
                                         sizeof(detail), None, None):
             DestroyDeviceInfoList(devinfo)
             raise RuntimeError, 'GetDeviceInterfaceDetail ' + format_err()
         if USE_RESIZE:
             res.append(detail.get_string())
         else:
             res.append(detail.DevicePath)
         m += 1
     DestroyDeviceInfoList(devinfo)
     return res
コード例 #24
0
def create_notification_struct(payload: bytes) -> \
        structs.SAdsNotificationHeader:
    """Create notification callback structure"""
    buf = b"\x00" * 12  # hNotification, nTimeStamp
    buf += struct.pack("<i", len(payload))
    buf += payload
    notification = structs.SAdsNotificationHeader()
    resize(notification, len(buf))
    memmove(
        pointer(notification),
        (ctypes.c_ubyte * len(buf)).from_buffer_copy(buf),
        sizeof(notification),
    )
    return notification
コード例 #25
0
ファイル: load.py プロジェクト: facebook/watchman
def load(fp, mutable: bool = True, value_encoding=None, value_errors=None):
    """Deserialize a BSER-encoded blob.

    @param fp: The file-object to deserialize.
    @type file:

    @param mutable: Whether to return mutable results.
    @type mutable: bool

    @param value_encoding: Optional codec to use to decode values. If
                           unspecified or None, return values as bytestrings.
    @type value_encoding: str

    @param value_errors: Optional error handler for codec. 'strict' by default.
                         The other most common argument is 'surrogateescape' on
                         Python 3. If value_encoding is None, this is ignored.
    @type value_errors: str
    """
    buf = ctypes.create_string_buffer(8192)
    SNIFF_BUFFER_SIZE = len(EMPTY_HEADER)
    # pyre-fixme[16]: `int` has no attribute `from_buffer`.
    # pyre-fixme[58]: `*` is not supported for operand types `Type[ctypes.c_char]`
    #  and `int`.
    header = (ctypes.c_char * SNIFF_BUFFER_SIZE).from_buffer(buf)
    read_len = _read_bytes(fp, header)
    if read_len < len(header):
        return None

    # pyre-fixme[16]: Module `pywatchman` has no attribute `bser`.
    total_len = bser.pdu_len(buf)
    if total_len > len(buf):
        ctypes.resize(buf, total_len)

    # pyre-fixme[58]: `*` is not supported for operand types `Type[ctypes.c_char]`
    #  and `Any`.
    body = (ctypes.c_char * (total_len - len(header))).from_buffer(buf, len(header))
    read_len = _read_bytes(fp, body)
    if read_len < len(body):
        raise RuntimeError("bser data ended early")

    # pyre-fixme[16]: Module `pywatchman` has no attribute `bser`.
    return bser.loads(
        # pyre-fixme[58]: `*` is not supported for operand types
        #  `Type[ctypes.c_char]` and `Any`.
        (ctypes.c_char * total_len).from_buffer(buf, 0),
        mutable,
        value_encoding,
        value_errors,
    )
コード例 #26
0
ファイル: efi.py プロジェクト: kirkboy/bits
def print_variables():
    name = ctypes.create_unicode_buffer("")
    size = ctypes.c_ulong(ctypes.sizeof(name))
    guid = GUID()
    while True:
        status = call(system_table.RuntimeServices.contents.GetNextVariableName, ctypes.addressof(size), ctypes.addressof(name), ctypes.addressof(guid))
        if status == EFI_NOT_FOUND:
            break
        if status == EFI_BUFFER_TOO_SMALL:
            ctypes.resize(name, size.value)
            continue
        check_status(status)
        print name.value, guid
        data, attributes, data_size = get_variable(name, guid)
        print "attributes={:#x} size={} data:".format(attributes, data_size)
        print bits.dumpmem(data.raw)
コード例 #27
0
def GetDevicePaths(uuid, db, field, cid):
    guid = parse_uuid(uuid)
    hdi = SAPI.SetupDiGetClassDevsW(byref(guid), None, None, DIGCF_DEVINTERFACE | DIGCF_PRESENT)
    dd = SP_DEVINFO_DATA(sizeof(SP_DEVINFO_DATA))
    did = SP_DEVICE_INTERFACE_DATA(sizeof(SP_DEVICE_INTERFACE_DATA))
    i = 0
    while SAPI.SetupDiEnumDeviceInterfaces(hdi, None, byref(guid), i, byref(did)):
        i += 1
        size = DWORD(0)
        SAPI.SetupDiGetDeviceInterfaceDetailW(hdi, byref(did), None, 0, byref(size), 0)
        didd = PSP_DEVICE_INTERFACE_DETAIL_DATA()
        resize(didd, size.value)
        didd.cbSize = sizeof(PSP_DEVICE_INTERFACE_DETAIL_DATA) - sizeof(WCHAR * 1)
        SAPI.SetupDiGetDeviceInterfaceDetailW(hdi, byref(did), byref(didd), size, byref(size), byref(dd))
        path = wstring_at(byref(didd, sizeof(DWORD)))
        db = DeviceConnect(path, db, field, cid)
    return db
コード例 #28
0
    def _increase_mem(self):
        """
        Doubles the size of the node array.
        The size must be increased on the _data
        member, since this ctype object owns the memory.
        """

        s_bytes = self._buf_nodes * sizeof(Node)
        if s_bytes != sizeof(self._data):
            raise ValueError("Internal Error!")

        resize(self._data, s_bytes*2)
        memset(byref(self._data, s_bytes), 0, s_bytes)

        self._buf_nodes *= 2
        # Renew the pointer since the arrays' memory
        # might have been moved.
        self._p = TrieDict._P(self._data)
コード例 #29
0
ファイル: blueforsValves.py プロジェクト: CamilleBo/pyHegel
 def get_all_dev_interface(ClassGuid, Enumerator, Flags, search_interface=GUID_INTERFACE_USB_DEVICE):
     if not Flags & DIGCF_DEVICEINTERFACE:
         raise ValueError, "The DIGCF_DEVICEINTERFACE flag is required here."
     devinfo = GetClassDevs(ClassGuid, Enumerator, 0, Flags)
     if devinfo == INVALID_HANDLE_VALUE:
         raise RuntimeError, format_err()
     m=0
     dinter = SP_DEVICE_INTERFACE_DATA()
     dinter.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA)
     bufsize = DWORD()
     res = []
     while True:
         if not EnumDeviceInterfaces(devinfo, None, search_interface, m, dinter):
             err = get_last_error()
             if err != ERROR_NO_MORE_ITEMS:
                 DestroyDeviceInfoList(devinfo)
                 raise RuntimeError, 'EnumDeviceInterface '+format_err(err)
             break
         # Find required bufsize
         GetDeviceInterfaceDetail(devinfo, dinter, None, 0, bufsize, None)
         if USE_RESIZE:
             detail = SP_DEVICE_INTERFACE_DETAIL_DATA()
             resize(detail, bufsize.value)
             detailp = byref(detail)
         else:
             detail = detail_gen(bufsize.value)
             # cast is needed because GetDeviceInterfaceDetail is defined to require
             #  POINTER(SP_DEVICE_INTERFACE_DETAIL_DATA)
             # Instead of a cast the object could also be a subclass
             detailp = cast(pointer(detail), POINTER(SP_DEVICE_INTERFACE_DETAIL_DATA))
         detail.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)
         # Note that the last argument could be used to have the SP_DEVINFO_DATA
         # reference of this entry that can be used with GetDeviceInstanceId
         if not GetDeviceInterfaceDetail(devinfo, dinter, detailp, sizeof(detail), None, None):
             DestroyDeviceInfoList(devinfo)
             raise RuntimeError, 'GetDeviceInterfaceDetail '+format_err()
         if USE_RESIZE:
             res.append(detail.get_string())
         else:
             res.append(detail.DevicePath)
         m += 1
     DestroyDeviceInfoList(devinfo)
     return res
コード例 #30
0
ファイル: winusbpy.py プロジェクト: felHR85/WinUsbPy
	def list_usb_devices(self, **kwargs):
		self.device_paths = []
		value = 0x00000000
		try:
			if kwargs["default"] == True:
				value |= DIGCF_DEFAULT
			if kwargs["present"] == True:
				value |= DIGCF_PRESENT
			if kwargs["allclasses"] == True:
				value |= DIGCF_ALLCLASSES
			if kwargs["profile"] == True:
				value |= DIGCF_PROFILE
			if kwargs["deviceinterface"] == True:
				value |= DIGCF_DEVICE_INTERFACE
		except KeyError:
			if value == 0x00000000:
				value = 0x00000010
			pass

		flags = DWORD(value)
		self.handle = self.api.exec_function_setupapi(SetupDiGetClassDevs, byref(self.guid), None, None, flags)

		sp_device_interface_data = SpDeviceInterfaceData()
		sp_device_interface_data.cb_size = sizeof(sp_device_interface_data)
		sp_device_interface_detail_data = SpDeviceInterfaceDetailData()
		sp_device_info_data = SpDevinfoData()
		sp_device_info_data.cb_size = sizeof(sp_device_info_data)
		i = 0
		required_size = c_ulong(0)
		member_index = DWORD(i)

		while self.api.exec_function_setupapi(SetupDiEnumDeviceInterfaces , self.handle, None, byref(self.guid), member_index, byref(sp_device_interface_data)):
			self.api.exec_function_setupapi(SetupDiGetDeviceInterfaceDetail, self.handle, byref(sp_device_interface_data), None, 0, byref(required_size), None)
			resize(sp_device_interface_detail_data, required_size.value)
			sp_device_interface_detail_data.cb_size = sizeof(SpDeviceInterfaceDetailData) - sizeof(WCHAR * 1)
			if self.api.exec_function_setupapi(SetupDiGetDeviceInterfaceDetail, self.handle, byref(sp_device_interface_data), byref(sp_device_interface_detail_data), required_size, byref(required_size), byref(sp_device_info_data)):
				path = wstring_at(byref(sp_device_interface_detail_data, sizeof(DWORD)))
				self.device_paths.append(path)
			i += 1
			member_index = DWORD(i)
			required_size = c_ulong(0)
			resize(sp_device_interface_detail_data, sizeof(SpDeviceInterfaceDetailData))
		return len(self.device_paths) > 0
コード例 #31
0
ファイル: scanner.py プロジェクト: dsedivec/mp3tool
 def _ensure_free(self, bytes_in_buf, min_bytes_free):
     buf_size = self._buf_size
     bytes_free = buf_size - bytes_in_buf
     if bytes_free < min_bytes_free:
         bytes_needed = min_bytes_free - bytes_free
         new_buf_size = max(buf_size * 2, buf_size + bytes_needed)
         if new_buf_size > self.MAX_BUFFER_SIZE:
             raise Exception("%r exceeds max buffer size %r"
                             % (new_buf_size, self.MAX_BUFFER_SIZE))
         orig_buf = self._orig_buf
         ctypes.resize(orig_buf, new_buf_size)
         new_buf_type = ctypes.c_char * new_buf_size
         buf_address = ctypes.addressof(orig_buf)
         self._buf = buf = new_buf_type.from_address(buf_address)
         self._view = view = memoryview(buf)
         self._buf_size = new_buf_size
     else:
         view = self._view
     # Return view as a convenience.
     return view
コード例 #32
0
def handlepacket(p):
    global N, img_list, imgvalue_list, img_map
    if p.haslayer(Raw):  # 找出有上网数据的
        load = p.load
        ack = p.ack
        try:
            ## 如果为图片相应,且带有HTTP头(即第一个图片TCP包)
            if 'Content-Type: image' in str(load):  # 如果为图片响应
                postfix = re.findall('image/(.*?)\\\\r', str(load))[0]  # 图片后缀
                length = int(
                    re.findall('Content-Length: (.*?)\\\\r',
                               str(load))[0])  # 图片数据长度
                ip_src = p['IP'].src  # 源头IP
                ip_dst = p['IP'].dst  # 目的IP
                img_list[ack] = [(postfix, length, ip_src, ip_dst)
                                 ]  # 0为图片信息(以下为图片二进制数据)
                img_load = load[load.find(b'\x0d\x0a\x0d\x0a') +
                                4:]  # 去除请求头部分,只要图片数据
                img_list[ack].append(img_load)
            ## 如果为某图片的后续数据包
            elif ack in list(img_list.keys()):
                img_load = load  # 所有load均为图片数据
                img_list[ack].append(img_load)
                img = bytes()
                postfix = img_list[ack][0][0]  # 图片后缀
                length = img_list[ack][0][1]  # 图片长度
                ip_src = img_list[ack][0][2]  # 源头IP
                ip_dst = img_list[ack][0][3]  # 目的IP
                for i in img_list[ack][1:]:
                    img += i
                if len(img) == length:  # 如果图片数据已经完整
                    imgname = '%d.%s' % (N, img_map[postfix])
                    with open('./images/%s/%s' % (target, imgname), 'wb') as f:
                        f.write(img)
                        img = Image.open(BytesIO(img))
                        img = resize(200, 200, img)
                        img_tk = ImageTk.PhotoImage(img)
                        imgvalue_list.append(img_tk)
                        Label(frame, image=imgvalue_list[-1],
                              bg='black').grid(row=(N - 1) // 4,
                                               column=(N - 1) % 4,
                                               padx=23,
                                               pady=3)
                        canvas.create_window((ww / 2, math.ceil(N / 4) * 105),
                                             window=frame)  #create_window
                        canvas['scrollregion'] = (0, 0, ww,
                                                  math.ceil(N / 4) * 210)
                        canvas.yview_moveto(1)
                        print('%s【driftnet】: saving image data as "%s"' %
                              (time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime()), imgname))
                        N += 1
        except:
            pass
コード例 #33
0
ファイル: load.py プロジェクト: llacb47/homebrfew-watchman
def load(fp, mutable=True, value_encoding=None, value_errors=None):
    """Deserialize a BSER-encoded blob.

    @param fp: The file-object to deserialize.
    @type file:

    @param mutable: Whether to return mutable results.
    @type mutable: bool

    @param value_encoding: Optional codec to use to decode values. If
                           unspecified or None, return values as bytestrings.
    @type value_encoding: str

    @param value_errors: Optional error handler for codec. 'strict' by default.
                         The other most common argument is 'surrogateescape' on
                         Python 3. If value_encoding is None, this is ignored.
    @type value_errors: str
    """
    buf = ctypes.create_string_buffer(8192)
    SNIFF_BUFFER_SIZE = len(EMPTY_HEADER)
    header = (ctypes.c_char * SNIFF_BUFFER_SIZE).from_buffer(buf)
    read_len = _read_bytes(fp, header)
    if read_len < len(header):
        return None

    total_len = bser.pdu_len(buf)
    if total_len > len(buf):
        ctypes.resize(buf, total_len)

    body = (ctypes.c_char * (total_len - len(header))).from_buffer(
        buf, len(header))
    read_len = _read_bytes(fp, body)
    if read_len < len(body):
        raise RuntimeError("bser data ended early")

    return bser.loads(
        (ctypes.c_char * total_len).from_buffer(buf, 0),
        mutable,
        value_encoding,
        value_errors,
    )
コード例 #34
0
ファイル: pybser.py プロジェクト: philipjameson/buck
def load(fp, mutable=True):
    """Deserialize bser from a file-like object"""
    buf = ctypes.create_string_buffer(8192)
    # 2 bytes marker, 1 byte int size, up to 8 bytes int64 value
    SNIFF_BUFFER_SIZE = 13

    header = (ctypes.c_char * SNIFF_BUFFER_SIZE).from_buffer(buf)
    num_bytes = _read_bytes(fp, header)
    if num_bytes < SNIFF_BUFFER_SIZE:
        return None

    expected_len, pos = _pdu_info_helper(header)
    total_len = expected_len + pos
    if len(buf) < total_len:
        ctypes.resize(buf, total_len)
    body = (ctypes.c_char * (total_len - len(header))).from_buffer(buf, len(header))
    num_bytes = _read_bytes(fp, body)
    if num_bytes < (total_len - len(header)):
        raise RuntimeError('bser data ended early')

    return _bser_loads_recursive(buf, pos, mutable)[0]
コード例 #35
0
ファイル: load.py プロジェクト: Stevenzwzhai/watchman
def load(fp, mutable=True, value_encoding=None, value_errors=None):
    """Deserialize a BSER-encoded blob.

    @param fp: The file-object to deserialize.
    @type file:

    @param mutable: Whether to return mutable results.
    @type mutable: bool

    @param value_encoding: Optional codec to use to decode values. If
                           unspecified or None, return values as bytestrings.
    @type value_encoding: str

    @param value_errors: Optional error handler for codec. 'strict' by default.
                         The other most common argument is 'surrogateescape' on
                         Python 3. If value_encoding is None, this is ignored.
    @type value_errors: str
    """
    buf = ctypes.create_string_buffer(8192)
    SNIFF_BUFFER_SIZE = len(EMPTY_HEADER)
    header = (ctypes.c_char * SNIFF_BUFFER_SIZE).from_buffer(buf)
    read_len = _read_bytes(fp, header)
    if read_len < len(header):
        return None

    total_len = bser.pdu_len(buf)
    if total_len > len(buf):
        ctypes.resize(buf, total_len)

    body = (ctypes.c_char * (total_len - len(header))).from_buffer(buf, len(header))
    read_len = _read_bytes(fp, body)
    if read_len < len(body):
        raise RuntimeError("bser data ended early")

    return bser.loads(
        (ctypes.c_char * total_len).from_buffer(buf, 0),
        mutable,
        value_encoding,
        value_errors,
    )
コード例 #36
0
def load(fp, mutable=True):
    """Deserialize bser from a file-like object"""
    buf = ctypes.create_string_buffer(8192)
    # 2 bytes marker, 1 byte int size, up to 8 bytes int64 value
    SNIFF_BUFFER_SIZE = 13

    header = (ctypes.c_char * SNIFF_BUFFER_SIZE).from_buffer(buf)
    num_bytes = _read_bytes(fp, header)
    if num_bytes < SNIFF_BUFFER_SIZE:
        return None

    expected_len, pos = _pdu_info_helper(header)
    total_len = expected_len + pos
    if len(buf) < total_len:
        ctypes.resize(buf, total_len)
    body = (ctypes.c_char * (total_len - len(header))).from_buffer(
        buf, len(header))
    num_bytes = _read_bytes(fp, body)
    if num_bytes < (total_len - len(header)):
        raise RuntimeError('bser data ended early')

    return _bser_loads_recursive(buf, pos, mutable)[0]
コード例 #37
0
ファイル: setupapi.py プロジェクト: rnestler/pyjoulescope
def device_interface_guid_to_paths(guid):
    """Find the connected devices that match the provided GUID.
    
    :param guid: The deviceInterfaceGUID to match.
    :return: The list of path strings.
    """
    paths = []
    flags = DWORD(DIGCF_PRESENT | DIGCF_DEVICE_INTERFACE)
    guid = GUID(guid)
    handle = SetupDiGetClassDevs(byref(guid), None, None, flags)
    if handle is None:
        raise RuntimeError('SetupDiGetClassDevs invalid')

    sp_device_interface_data = SpDeviceInterfaceData()
    sp_device_info_data = SpDevinfoData()
    member_index = 0

    while SetupDiEnumDeviceInterfaces(handle, None, byref(guid),
                                      DWORD(member_index),
                                      byref(sp_device_interface_data)):
        required_size = c_ulong(0)
        bResult = SetupDiGetDeviceInterfaceDetail(
            handle, byref(sp_device_interface_data), None, 0,
            byref(required_size), None)
        sp_device_interface_detail_data = SpDeviceInterfaceDetailData()
        resize(sp_device_interface_detail_data, required_size.value)
        sp_device_interface_detail_data.cb_size = sizeof(
            SpDeviceInterfaceDetailData)
        bResult = SetupDiGetDeviceInterfaceDetail(
            handle, byref(sp_device_interface_data),
            byref(sp_device_interface_detail_data), required_size,
            byref(required_size), byref(sp_device_info_data))
        if bResult:
            path = wstring_at(
                byref(sp_device_interface_detail_data, sizeof(DWORD)))
            paths.append(path)
        member_index += 1
    SetupDiDestroyDeviceInfoList(handle)
    return paths
コード例 #38
0
 def GetAllFeature(self, hCamera):
     """ Retrieve a camera setting using the feature id definitions. """
     BufferSize = C.c_int(0)
     rc = self.__lib.PxLGetCameraFeatures(
         hCamera,
         PxLapi.FEATURE_ALL,
         None,
         C.byref(BufferSize))
     if rc < 0:
         return (rc, 0)
     else:
         FeatureInfo = CAMERA_FEATURES()
         C.resize(FeatureInfo, BufferSize.value)
         rc = self.__lib.PxLGetCameraFeatures(
             hCamera,
             PxLapi.FEATURE_ALL,
             C.byref(FeatureInfo),
             C.byref(BufferSize))
         if rc < 0:
             return (rc, 0)
         else:
             return rc, FeatureInfo
コード例 #39
0
ファイル: wincertstore.py プロジェクト: DamirAinullin/PTVS
    def _get_enhkey(self, flag):
        pCertCtx = pointer(self)
        enhkey = CERT_ENHKEY_USAGE()
        size = DWORD()

        res = CertGetEnhancedKeyUsage(pCertCtx, flag, None, pointer(size))
        if res == 0:
            return self._enhkey_error()

        resize(enhkey, size.value)
        res = CertGetEnhancedKeyUsage(pCertCtx, flag, pointer(enhkey),
                                      pointer(size))
        if res == 0:
            return self._enhkey_error()

        oids = set()
        for i in range(enhkey.cUsageIdentifier):
            oid = enhkey.rgpszUsageIdentifier[i]
            if oid:
                if PY3:
                    oid = oid.decode("ascii")
                oids.add(oid)
        return oids
コード例 #40
0
    def _get_enhkey(self, flag):
        pCertCtx = pointer(self)
        enhkey = CERT_ENHKEY_USAGE()
        size = DWORD()

        res = CertGetEnhancedKeyUsage(pCertCtx, flag, None, pointer(size))
        if res == 0:
            return self._enhkey_error()

        resize(enhkey, size.value)
        res = CertGetEnhancedKeyUsage(pCertCtx, flag, pointer(enhkey),
                                      pointer(size))
        if res == 0:
            return self._enhkey_error()

        oids = set()
        for i in range(enhkey.cUsageIdentifier):
            oid = enhkey.rgpszUsageIdentifier[i]
            if oid:
                if PY3:
                    oid = oid.decode("ascii")
                oids.add(oid)
        return oids
コード例 #41
0
ファイル: core.py プロジェクト: wolneykien/cx
    def recv(self):
        """
        Receive a request message from the client
        """
        msgdata = (c_ubyte * NORM_MSG_SIZE)()
        msg = mempair(p9msg, msgdata)
        (baddr, blen) = msg.databuf()
        l = libc.recv(self.__clsock, baddr, blen, 0)
        hdr = msg.car()
        if l > sizeof(hdr):
            if hdr.size > l:
                if hdr.size > MAX_MSG_SIZE:
                    raise IOError ("The message is too large: %d bytes" % hdr.size)
                resize(msgdata, hdr.size)
                (baddr, blen) = msg.databuf()
                l2 = libc.recv(self.__clsock, baddr + hdr.size - l, blen - l, 0)
                if l2 > 0:
                    l += l2
                else:
                    raise IOError ("Unable to read the %d remaining bytes" % blen - l)
        else:
            raise IOError ("Unable to read the message")

        return (l, msg)
コード例 #42
0
def get_device_path(h_info, interface_data, ptr_info_data=None):
    """"Returns Hardware device path
    Parameters:
        h_info,         interface set info handler
        interface_data, device interface enumeration data
        ptr_info_data,  pointer to SP_DEVINFO_DATA() instance to receive details
    """
    required_size = c_ulong(0)

    dev_inter_detail_data = SP_DEVICE_INTERFACE_DETAIL_DATA()
    dev_inter_detail_data.cb_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)

    # get actual storage requirement
    SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data), None, 0,
                                    byref(required_size), None)
    ctypes.resize(dev_inter_detail_data, required_size.value)

    # read value
    SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data),
                                    byref(dev_inter_detail_data),
                                    required_size, None, ptr_info_data)

    # extract string only
    return dev_inter_detail_data.get_string()
コード例 #43
0
ファイル: efi.py プロジェクト: kirkboy/bits
 def _set_name(self, name):
     b = ctypes.create_unicode_buffer(name)
     ctypes.resize(self, ctypes.sizeof(self.__class__) + ctypes.sizeof(b))
     ctypes.memmove(ctypes.addressof(self) + ctypes.sizeof(self.__class__), ctypes.addressof(b), ctypes.sizeof(b))
     self.Size = ctypes.sizeof(b)
コード例 #44
0
def growTrie():
    # Originally I wrote to disk then pulled it back because most methods to
    # extend C structured array requires having both the old and new array in
    # memory at once for some period of time, but since our columns are individual
    # arrays, we only require 28% of the RAM that doing it as a single array takes.
    # This is also why we extend SEQ first.
    global A
    global C
    global G
    global T
    global COUNT
    global SEQ

    if arrayKind == 'numpy':
        SEQ = numpy.concatenate((SEQ,numpy.zeros(10000000, dtype='int64')))
        A = numpy.concatenate((A,numpy.zeros(10000000, dtype='uint32')))
        C = numpy.concatenate((C,numpy.zeros(10000000, dtype='uint32')))
        G = numpy.concatenate((G,numpy.zeros(10000000, dtype='uint32')))
        T = numpy.concatenate((T,numpy.zeros(10000000, dtype='uint32')))
        COUNT = numpy.concatenate((COUNT,numpy.zeros(10000000, dtype='uint32')))
    elif arrayKind == 'ctypes':
        newSize = A._length_+10000000
        ctypes.resize(SEQ, ctypes.sizeof(SEQ._type_)*newSize)
        SEQ = (SEQ._type_*newSize).from_address(ctypes.addressof(SEQ))
        ctypes.resize(A, ctypes.sizeof(A._type_)*newSize)
        A = (A._type_*newSize).from_address(ctypes.addressof(A))
        ctypes.resize(C, ctypes.sizeof(C._type_)*newSize)
        C = (C._type_*newSize).from_address(ctypes.addressof(C))
        ctypes.resize(G, ctypes.sizeof(G._type_)*newSize)
        G = (A._type_*newSize).from_address(ctypes.addressof(G))
        ctypes.resize(T, ctypes.sizeof(T._type_)*newSize)
        T = (A._type_*newSize).from_address(ctypes.addressof(T))
        ctypes.resize(COUNT, ctypes.sizeof(COUNT._type_)*newSize)
        COUNT = (A._type_*newSize).from_address(ctypes.addressof(COUNT))
    elif arrayKind == 'cffi':
        try:
            tempA     = A;     A     = ffi.new("uint32_t[]", len(A)+10000000);     ffi.memmove(A,tempA,len(tempA)*(ffi.sizeof(A)/len(A)))
            tempC     = C;     C     = ffi.new("uint32_t[]", len(C)+10000000);     ffi.memmove(C,tempC,len(tempC)*(ffi.sizeof(C)/len(C)))
            tempG     = G;     G     = ffi.new("uint32_t[]", len(G)+10000000);     ffi.memmove(G,tempG,len(tempG)*(ffi.sizeof(G)/len(G)))
            tempT     = T;     T     = ffi.new("uint32_t[]", len(T)+10000000);     ffi.memmove(T,tempT,len(tempT)*(ffi.sizeof(T)/len(T)))
            tempCOUNT = COUNT; COUNT = ffi.new("uint32_t[]", len(COUNT)+10000000); ffi.memmove(COUNT,tempCOUNT,len(tempCOUNT)*(ffi.sizeof(COUNT)/len(COUNT)))
            tempSEQ   = SEQ;   SEQ   = ffi.new("int64_t[]", len(SEQ)+10000000);    ffi.memmove(SEQ,tempSEQ,len(tempSEQ)*(ffi.sizeof(SEQ)/len(SEQ)))
        except AttributeError:
            print 'ERROR! Your version of python does not fully support cffi! Please upgrade, or set the intial amount of RAM to something larger.'
            exit()
    getRAM()
コード例 #45
0
    def list_usb_devices(self, **kwargs):
        self.device_paths = {}
        value = 0x00000000
        try:
            if kwargs.get("default"):
                value |= DIGCF_DEFAULT
            if kwargs.get("present"):
                value |= DIGCF_PRESENT
            if kwargs.get("allclasses"):
                value |= DIGCF_ALLCLASSES
            if kwargs.get("profile"):
                value |= DIGCF_PROFILE
            if kwargs.get("deviceinterface"):
                value |= DIGCF_DEVICE_INTERFACE
        except KeyError:
            if value == 0x00000000:
                value = 0x00000010
            pass

        flags = DWORD(value)
        self.handle = self.api.exec_function_setupapi(SetupDiGetClassDevs, byref(self.usb_winusb_guid), None, None, flags)

        sp_device_interface_data = SpDeviceInterfaceData()
        sp_device_interface_data.cb_size = sizeof(sp_device_interface_data)
        sp_device_interface_detail_data = SpDeviceInterfaceDetailData()
        sp_device_info_data = SpDevinfoData()
        sp_device_info_data.cb_size = sizeof(sp_device_info_data)

        i = 0
        required_size = DWORD(0)
        member_index = DWORD(i)
        cb_sizes = (8, 6, 5)  # different on 64 bit / 32 bit etc

        while self.api.exec_function_setupapi(SetupDiEnumDeviceInterfaces, self.handle, None, byref(self.usb_winusb_guid),
                                              member_index, byref(sp_device_interface_data)):
            self.api.exec_function_setupapi(SetupDiGetDeviceInterfaceDetail, self.handle,
                                            byref(sp_device_interface_data), None, 0, byref(required_size), None)
            resize(sp_device_interface_detail_data, required_size.value)


            path = None
            for cb_size in cb_sizes:
                sp_device_interface_detail_data.cb_size = cb_size
                ret = self.api.exec_function_setupapi(SetupDiGetDeviceInterfaceDetail, self.handle,
                                               byref(sp_device_interface_data), byref(sp_device_interface_detail_data),
                                               required_size, byref(required_size), byref(sp_device_info_data))
                if ret:
                    cb_sizes = (cb_size, )
                    path = wstring_at(byref(sp_device_interface_detail_data, sizeof(DWORD)))
                    break
            if path is None:
                raise ctypes.WinError()

            # friendly name
            name = path
            buff_friendly_name = ctypes.create_unicode_buffer(250)
            if self.api.exec_function_setupapi(SetupDiGetDeviceRegistryProperty, self.handle,
                                               byref(sp_device_info_data),
                                               SPDRP_FRIENDLYNAME,
                                               None,
                                               ctypes.byref(buff_friendly_name),
                                               ctypes.sizeof(buff_friendly_name) - 1,
                                               None):

                name = buff_friendly_name.value
            else:
                print(ctypes.WinError())
            self.device_paths[name] = path
            i += 1
            member_index = DWORD(i)
            required_size = c_ulong(0)
            resize(sp_device_interface_detail_data, sizeof(SpDeviceInterfaceDetailData))
        return self.device_paths
コード例 #46
0
def get_integrity_level():
    '''from http://www.programcreek.com/python/example/3211/ctypes.c_long'''

    if sys.platform != 'win32':
        if os.geteuid() != 0:
            return "Medium"
        else:
            return "High"

    mapping = {
        0x0000: u'Untrusted',
        0x1000: u'Low',
        0x2000: u'Medium',
        0x2100: u'Medium high',
        0x3000: u'High',
        0x4000: u'System',
        0x5000: u'Protected process',
    }

    BOOL = ctypes.c_long
    DWORD = ctypes.c_ulong
    HANDLE = ctypes.c_void_p

    class SID_AND_ATTRIBUTES(ctypes.Structure):
        _fields_ = [
            ('Sid', ctypes.c_void_p),
            ('Attributes', DWORD),
        ]

    class TOKEN_MANDATORY_LABEL(ctypes.Structure):
        _fields_ = [
            ('Label', SID_AND_ATTRIBUTES),
        ]

    TOKEN_READ = DWORD(0x20008)
    TokenIntegrityLevel = ctypes.c_int(25)
    ERROR_INSUFFICIENT_BUFFER = 122

    ctypes.windll.kernel32.GetLastError.argtypes = ()
    ctypes.windll.kernel32.GetLastError.restype = DWORD
    ctypes.windll.kernel32.GetCurrentProcess.argtypes = ()
    ctypes.windll.kernel32.GetCurrentProcess.restype = ctypes.c_void_p
    ctypes.windll.advapi32.OpenProcessToken.argtypes = (HANDLE, DWORD,
                                                        ctypes.POINTER(HANDLE))
    ctypes.windll.advapi32.OpenProcessToken.restype = BOOL
    ctypes.windll.advapi32.GetTokenInformation.argtypes = (
        HANDLE, ctypes.c_long, ctypes.c_void_p, DWORD, ctypes.POINTER(DWORD))
    ctypes.windll.advapi32.GetTokenInformation.restype = BOOL
    ctypes.windll.advapi32.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
    ctypes.windll.advapi32.GetSidSubAuthorityCount.restype = ctypes.POINTER(
        ctypes.c_ubyte)
    ctypes.windll.advapi32.GetSidSubAuthority.argtypes = (ctypes.c_void_p,
                                                          DWORD)
    ctypes.windll.advapi32.GetSidSubAuthority.restype = ctypes.POINTER(DWORD)

    token = ctypes.c_void_p()
    proc_handle = ctypes.windll.kernel32.GetCurrentProcess()
    if not ctypes.windll.advapi32.OpenProcessToken(proc_handle, TOKEN_READ,
                                                   ctypes.byref(token)):
        logging.error('Failed to get process token')
        return None

    if token.value == 0:
        logging.error('Got a NULL token')
        return None
    try:
        info_size = DWORD()
        if ctypes.windll.advapi32.GetTokenInformation(token,
                                                      TokenIntegrityLevel,
                                                      ctypes.c_void_p(),
                                                      info_size,
                                                      ctypes.byref(info_size)):
            logging.error('GetTokenInformation() failed expectation')
            return None

        if info_size.value == 0:
            logging.error('GetTokenInformation() returned size 0')
            return None

        if ctypes.windll.kernel32.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
            logging.error('GetTokenInformation(): Unknown error: %d',
                          ctypes.windll.kernel32.GetLastError())
            return None

        token_info = TOKEN_MANDATORY_LABEL()
        ctypes.resize(token_info, info_size.value)
        if not ctypes.windll.advapi32.GetTokenInformation(
                token, TokenIntegrityLevel, ctypes.byref(token_info),
                info_size, ctypes.byref(info_size)):
            logging.error(
                'GetTokenInformation(): Unknown error with buffer size %d: %d',
                info_size.value, ctypes.windll.kernel32.GetLastError())
            return None

        p_sid_size = ctypes.windll.advapi32.GetSidSubAuthorityCount(
            token_info.Label.Sid)
        res = ctypes.windll.advapi32.GetSidSubAuthority(
            token_info.Label.Sid, p_sid_size.contents.value - 1)
        value = res.contents.value
        return mapping.get(value) or u'0x%04x' % value

    finally:
        ctypes.windll.kernel32.CloseHandle(token)
コード例 #47
0
 def ensure_size(self, size):
     while ctypes.sizeof(self.buf) - self.wpos < size:
         ctypes.resize(self.buf, ctypes.sizeof(self.buf) * 2)
コード例 #48
0
ファイル: win.py プロジェクト: rmoorman/luci-py
def get_integrity_level():
    """Returns the integrity level of the current process as a string.

  TODO(maruel): It'd be nice to make it work on cygwin. The problem is that
  ctypes.windll is unaccessible and it is not known to the author how to use
  stdcall convention through ctypes.cdll.
  """
    if get_os_version_number() == u'5.1':
        # Integrity level is Vista+.
        return None

    mapping = {
        0x0000: u'untrusted',
        0x1000: u'low',
        0x2000: u'medium',
        0x2100: u'medium high',
        0x3000: u'high',
        0x4000: u'system',
        0x5000: u'protected process',
    }

    # This was specifically written this way to work on cygwin except for the
    # windll part. If someone can come up with a way to do stdcall on cygwin, that
    # would be appreciated.
    BOOL = ctypes.c_long
    DWORD = ctypes.c_ulong
    HANDLE = ctypes.c_void_p

    class SID_AND_ATTRIBUTES(ctypes.Structure):
        _fields_ = [
            ('Sid', ctypes.c_void_p),
            ('Attributes', DWORD),
        ]

    class TOKEN_MANDATORY_LABEL(ctypes.Structure):
        _fields_ = [
            ('Label', SID_AND_ATTRIBUTES),
        ]

    TOKEN_READ = DWORD(0x20008)
    # Use the same casing as in the C declaration:
    # https://msdn.microsoft.com/library/windows/desktop/aa379626.aspx
    TokenIntegrityLevel = ctypes.c_int(25)
    ERROR_INSUFFICIENT_BUFFER = 122

    # All the functions used locally. First open the process' token, then query
    # the SID to know its integrity level.
    ctypes.windll.kernel32.GetLastError.argtypes = ()
    ctypes.windll.kernel32.GetLastError.restype = DWORD
    ctypes.windll.kernel32.GetCurrentProcess.argtypes = ()
    ctypes.windll.kernel32.GetCurrentProcess.restype = ctypes.c_void_p
    ctypes.windll.advapi32.OpenProcessToken.argtypes = (HANDLE, DWORD,
                                                        ctypes.POINTER(HANDLE))
    ctypes.windll.advapi32.OpenProcessToken.restype = BOOL
    ctypes.windll.advapi32.GetTokenInformation.argtypes = (
        HANDLE, ctypes.c_long, ctypes.c_void_p, DWORD, ctypes.POINTER(DWORD))
    ctypes.windll.advapi32.GetTokenInformation.restype = BOOL
    ctypes.windll.advapi32.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
    ctypes.windll.advapi32.GetSidSubAuthorityCount.restype = ctypes.POINTER(
        ctypes.c_ubyte)
    ctypes.windll.advapi32.GetSidSubAuthority.argtypes = (ctypes.c_void_p,
                                                          DWORD)
    ctypes.windll.advapi32.GetSidSubAuthority.restype = ctypes.POINTER(DWORD)

    # First open the current process token, query it, then close everything.
    token = ctypes.c_void_p()
    proc_handle = ctypes.windll.kernel32.GetCurrentProcess()
    if not ctypes.windll.advapi32.OpenProcessToken(proc_handle, TOKEN_READ,
                                                   ctypes.byref(token)):
        logging.error('Failed to get process\' token')
        return None
    if token.value == 0:
        logging.error('Got a NULL token')
        return None
    try:
        # The size of the structure is dynamic because the TOKEN_MANDATORY_LABEL
        # used will have the SID appened right after the TOKEN_MANDATORY_LABEL in
        # the heap allocated memory block, with .Label.Sid pointing to it.
        info_size = DWORD()
        if ctypes.windll.advapi32.GetTokenInformation(token,
                                                      TokenIntegrityLevel,
                                                      ctypes.c_void_p(),
                                                      info_size,
                                                      ctypes.byref(info_size)):
            logging.error('GetTokenInformation() failed expectation')
            return None
        if info_size.value == 0:
            logging.error('GetTokenInformation() returned size 0')
            return None
        if ctypes.windll.kernel32.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
            logging.error('GetTokenInformation(): Unknown error: %d',
                          ctypes.windll.kernel32.GetLastError())
            return None
        token_info = TOKEN_MANDATORY_LABEL()
        ctypes.resize(token_info, info_size.value)
        if not ctypes.windll.advapi32.GetTokenInformation(
                token, TokenIntegrityLevel, ctypes.byref(token_info),
                info_size, ctypes.byref(info_size)):
            logging.error(
                'GetTokenInformation(): Unknown error with buffer size %d: %d',
                info_size.value, ctypes.windll.kernel32.GetLastError())
            return None
        p_sid_size = ctypes.windll.advapi32.GetSidSubAuthorityCount(
            token_info.Label.Sid)
        res = ctypes.windll.advapi32.GetSidSubAuthority(
            token_info.Label.Sid, p_sid_size.contents.value - 1)
        value = res.contents.value
        return mapping.get(value) or u'0x%04x' % value
    finally:
        ctypes.windll.kernel32.CloseHandle(token)
コード例 #49
0
ファイル: pybser.py プロジェクト: SeleniumHQ/buck
 def ensure_size(self, size):
     while ctypes.sizeof(self.buf) - self.wpos < size:
         ctypes.resize(self.buf, ctypes.sizeof(self.buf) * 2)
コード例 #50
0
def DeviceConnect(path, db, field, cid):
    if debug: print('Connecting to:', path)

    cached = 1
    device_found = -1
    for j in range(len(db)):
        address = db[j]['hwid'].split('_')[1]
        if address in path:
            device_found = j
            cached = db[j]['status'] != 'connected'
    if device_found < 0:
        return db

    hDevice = windll.kernel32.CreateFileW(path, GENERIC_READ,
                                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                                          None, OPEN_EXISTING, 0, None)
    ServicesBufferCount = USHORT()
    BT.BluetoothGATTGetServices(hDevice, 0, None, byref(ServicesBufferCount),
                                BLUETOOTH_GATT_FLAG_NONE)
    ServicesBuffer = new(BTH_LE_GATT_SERVICE * ServicesBufferCount.value)
    BT.BluetoothGATTGetServices(hDevice, ServicesBufferCount,
                                byref(ServicesBuffer),
                                byref(ServicesBufferCount),
                                BLUETOOTH_GATT_FLAG_NONE)

    for Service in ServicesBuffer:
        CharacteristicsBufferCount = USHORT(0)
        hr = BT.BluetoothGATTGetCharacteristics(
            hDevice, byref(Service), 0, None,
            byref(CharacteristicsBufferCount), BLUETOOTH_GATT_FLAG_NONE)
        CharacteristicsBuffer = new(BTH_LE_GATT_CHARACTERISTIC *
                                    CharacteristicsBufferCount.value)
        CharacteristicsBufferActual = USHORT(0)
        BT.BluetoothGATTGetCharacteristics(hDevice, byref(Service),
                                           CharacteristicsBufferCount,
                                           byref(CharacteristicsBuffer),
                                           byref(CharacteristicsBufferActual),
                                           BLUETOOTH_GATT_FLAG_NONE)

        for Characteristic in CharacteristicsBuffer:
            uuid = Characteristic.CharacteristicUuid.ShortUuid
            charValueDataSize = USHORT()
            hr = BT.BluetoothGATTGetCharacteristicValue(
                hDevice, byref(Characteristic), 0, None,
                byref(charValueDataSize), BLUETOOTH_GATT_FLAG_NONE
                if cached else BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_DEVICE)

            pCharValueBuffer = BTH_LE_GATT_CHARACTERISTIC_VALUE()
            resize(pCharValueBuffer, charValueDataSize.value)

            hr = BT.BluetoothGATTGetCharacteristicValue(
                hDevice, byref(Characteristic), charValueDataSize,
                byref(pCharValueBuffer), None, BLUETOOTH_GATT_FLAG_NONE
                if cached else BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_DEVICE)

            StringValue = string_at(byref(pCharValueBuffer, sizeof(ULONG)))
            arr = bytearray(StringValue)

            if uuid == 0x2A19:  # battery level
                value = 0 if len(arr) < 1 else arr[0]
            elif uuid == 0x2A01:  # appearance
                value = int(codecs.encode(arr, 'hex'), 16)
                value = Appearance(value)
            else:  # string
                value = str(StringValue.decode(errors='ignore'))

            if debug: print('\t%X' % uuid, value)

            if device_found != -1 and uuid == cid:
                db[device_found][field] = value

    return db
コード例 #51
0
ファイル: os_utilities.py プロジェクト: pombreda/luci-py
def get_integrity_level_win():
  """Returns the integrity level of the current process as a string.

  TODO(maruel): It'd be nice to make it work on cygwin. The problem is that
  ctypes.windll is unaccessible and it is not known to the author how to use
  stdcall convention through ctypes.cdll.
  """
  if sys.platform != 'win32':
    return None
  if get_os_version_number() == u'5.1':
    # Integrity level is Vista+.
    return None

  mapping = {
    0x0000: u'untrusted',
    0x1000: u'low',
    0x2000: u'medium',
    0x2100: u'medium high',
    0x3000: u'high',
    0x4000: u'system',
    0x5000: u'protected process',
  }

  # This was specifically written this way to work on cygwin except for the
  # windll part. If someone can come up with a way to do stdcall on cygwin, that
  # would be appreciated.
  BOOL = ctypes.c_long
  DWORD = ctypes.c_ulong
  HANDLE = ctypes.c_void_p
  class SID_AND_ATTRIBUTES(ctypes.Structure):
    _fields_ = [
      ('Sid', ctypes.c_void_p),
      ('Attributes', DWORD),
    ]

  class TOKEN_MANDATORY_LABEL(ctypes.Structure):
    _fields_ = [
      ('Label', SID_AND_ATTRIBUTES),
    ]

  TOKEN_READ = DWORD(0x20008)
  # Use the same casing as in the C declaration:
  # https://msdn.microsoft.com/library/windows/desktop/aa379626.aspx
  TokenIntegrityLevel = ctypes.c_int(25)
  ERROR_INSUFFICIENT_BUFFER = 122

  # All the functions used locally. First open the process' token, then query
  # the SID to know its integrity level.
  ctypes.windll.kernel32.GetLastError.argtypes = ()
  ctypes.windll.kernel32.GetLastError.restype = DWORD
  ctypes.windll.kernel32.GetCurrentProcess.argtypes = ()
  ctypes.windll.kernel32.GetCurrentProcess.restype = ctypes.c_void_p
  ctypes.windll.advapi32.OpenProcessToken.argtypes = (
      HANDLE, DWORD, ctypes.POINTER(HANDLE))
  ctypes.windll.advapi32.OpenProcessToken.restype = BOOL
  ctypes.windll.advapi32.GetTokenInformation.argtypes = (
      HANDLE, ctypes.c_long, ctypes.c_void_p, DWORD, ctypes.POINTER(DWORD))
  ctypes.windll.advapi32.GetTokenInformation.restype = BOOL
  ctypes.windll.advapi32.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
  ctypes.windll.advapi32.GetSidSubAuthorityCount.restype = ctypes.POINTER(
      ctypes.c_ubyte)
  ctypes.windll.advapi32.GetSidSubAuthority.argtypes = (ctypes.c_void_p, DWORD)
  ctypes.windll.advapi32.GetSidSubAuthority.restype = ctypes.POINTER(DWORD)

  # First open the current process token, query it, then close everything.
  token = ctypes.c_void_p()
  proc_handle = ctypes.windll.kernel32.GetCurrentProcess()
  if not ctypes.windll.advapi32.OpenProcessToken(
      proc_handle,
      TOKEN_READ,
      ctypes.byref(token)):
    logging.error('Failed to get process\' token')
    return None
  if token.value == 0:
    logging.error('Got a NULL token')
    return None
  try:
    # The size of the structure is dynamic because the TOKEN_MANDATORY_LABEL
    # used will have the SID appened right after the TOKEN_MANDATORY_LABEL in
    # the heap allocated memory block, with .Label.Sid pointing to it.
    info_size = DWORD()
    if ctypes.windll.advapi32.GetTokenInformation(
        token,
        TokenIntegrityLevel,
        ctypes.c_void_p(),
        info_size,
        ctypes.byref(info_size)):
      logging.error('GetTokenInformation() failed expectation')
      return None
    if info_size.value == 0:
      logging.error('GetTokenInformation() returned size 0')
      return None
    if ctypes.windll.kernel32.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
      logging.error(
          'GetTokenInformation(): Unknown error: %d',
          ctypes.windll.kernel32.GetLastError())
      return None
    token_info = TOKEN_MANDATORY_LABEL()
    ctypes.resize(token_info, info_size.value)
    if not ctypes.windll.advapi32.GetTokenInformation(
        token,
        TokenIntegrityLevel,
        ctypes.byref(token_info),
        info_size,
        ctypes.byref(info_size)):
      logging.error(
          'GetTokenInformation(): Unknown error with buffer size %d: %d',
          info_size.value,
          ctypes.windll.kernel32.GetLastError())
      return None
    p_sid_size = ctypes.windll.advapi32.GetSidSubAuthorityCount(
        token_info.Label.Sid)
    res = ctypes.windll.advapi32.GetSidSubAuthority(
        token_info.Label.Sid, p_sid_size.contents.value - 1)
    value = res.contents.value
    return mapping.get(value) or u'0x%04x' % value
  finally:
    ctypes.windll.kernel32.CloseHandle(token)
コード例 #52
0
def get_integrity_level():
    '''from http://www.programcreek.com/python/example/3211/ctypes.c_long'''

    if sys.platform != 'win32':
        if os.geteuid() != 0:
            return "Medium"
        else:
            return "High"

    mapping = {
        0x0000: u'Untrusted',
        0x1000: u'Low',
        0x2000: u'Medium',
        0x2100: u'Medium high',
        0x3000: u'High',
        0x4000: u'System',
        0x5000: u'Protected process',
    }

    BOOL = ctypes.c_long
    DWORD = ctypes.c_ulong
    HANDLE = ctypes.c_void_p

    class SID_AND_ATTRIBUTES(ctypes.Structure):
        _fields_ = [
            ('Sid', ctypes.c_void_p),
            ('Attributes', DWORD),
        ]

    class TOKEN_MANDATORY_LABEL(ctypes.Structure):
        _fields_ = [
            ('Label', SID_AND_ATTRIBUTES),
        ]

    TOKEN_READ = DWORD(0x20008)
    TokenIntegrityLevel = ctypes.c_int(25)
    ERROR_INSUFFICIENT_BUFFER = 122

    ctypes.windll.kernel32.GetLastError.argtypes = ()
    ctypes.windll.kernel32.GetLastError.restype = DWORD
    ctypes.windll.kernel32.GetCurrentProcess.argtypes = ()
    ctypes.windll.kernel32.GetCurrentProcess.restype = ctypes.c_void_p
    ctypes.windll.advapi32.OpenProcessToken.argtypes = (
            HANDLE, DWORD, ctypes.POINTER(HANDLE))
    ctypes.windll.advapi32.OpenProcessToken.restype = BOOL
    ctypes.windll.advapi32.GetTokenInformation.argtypes = (
            HANDLE, ctypes.c_long, ctypes.c_void_p, DWORD, ctypes.POINTER(DWORD))
    ctypes.windll.advapi32.GetTokenInformation.restype = BOOL
    ctypes.windll.advapi32.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
    ctypes.windll.advapi32.GetSidSubAuthorityCount.restype = ctypes.POINTER(
            ctypes.c_ubyte)
    ctypes.windll.advapi32.GetSidSubAuthority.argtypes = (ctypes.c_void_p, DWORD)
    ctypes.windll.advapi32.GetSidSubAuthority.restype = ctypes.POINTER(DWORD)

    token = ctypes.c_void_p()
    proc_handle = ctypes.windll.kernel32.GetCurrentProcess()
    if not ctypes.windll.advapi32.OpenProcessToken(
            proc_handle,
            TOKEN_READ,
            ctypes.byref(token)):
        logging.error('Failed to get process token')
        return None

    if token.value == 0:
        logging.error('Got a NULL token')
        return None
    try:
        info_size = DWORD()
        if ctypes.windll.advapi32.GetTokenInformation(
                token,
                TokenIntegrityLevel,
                ctypes.c_void_p(),
                info_size,
                ctypes.byref(info_size)):
            logging.error('GetTokenInformation() failed expectation')
            return None

        if info_size.value == 0:
            logging.error('GetTokenInformation() returned size 0')
            return None

        if ctypes.windll.kernel32.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
            logging.error(
                    'GetTokenInformation(): Unknown error: %d',
                    ctypes.windll.kernel32.GetLastError())
            return None

        token_info = TOKEN_MANDATORY_LABEL()
        ctypes.resize(token_info, info_size.value)
        if not ctypes.windll.advapi32.GetTokenInformation(
                token,
                TokenIntegrityLevel,
                ctypes.byref(token_info),
                info_size,
                ctypes.byref(info_size)):
            logging.error(
                    'GetTokenInformation(): Unknown error with buffer size %d: %d',
                    info_size.value,
                    ctypes.windll.kernel32.GetLastError())
            return None

        p_sid_size = ctypes.windll.advapi32.GetSidSubAuthorityCount(
                token_info.Label.Sid)
        res = ctypes.windll.advapi32.GetSidSubAuthority(
                token_info.Label.Sid, p_sid_size.contents.value - 1)
        value = res.contents.value
        return mapping.get(value) or u'0x%04x' % value

    finally:
        ctypes.windll.kernel32.CloseHandle(token)