Example #1
0
    def _get_c_cat(self, index):
        """Returns i-th description and i-th data range from the list of
        category descriptions with corresponding data ranges. end points of
        data interval.

        Rast_get_ith_cat(const struct Categories * 	pcats,
                         int 	i,
                         void * 	rast1,
                         void * 	rast2,
                         RASTER_MAP_TYPE 	data_type
                         )
        """
        min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
        max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
        lab = libraster.Rast_get_ith_cat(ctypes.byref(self.c_cats),
                                         index,
                                         ctypes.cast(min_cat, ctypes.c_void_p),
                                         ctypes.cast(max_cat, ctypes.c_void_p),
                                         self._gtype)
        # Manage C function Errors
        if lab == '':
            raise GrassError(_("Error executing: Rast_get_ith_cat"))
        if max_cat.contents.value == min_cat.contents.value:
            max_cat = None
        else:
            max_cat = max_cat.contents.value
        return lab, min_cat.contents.value, max_cat
Example #2
0
def launch_process(application,cmdline = None, priority = NORMAL_PRIORITY_CLASS):
  """
  <Purpose>
    Launches a new process.
  
  <Arguments>
    application:
      The path to the application to be started
    cmdline:
      The command line parameters that are to be used
    priority
      The priority of the process. See NORMAL_PRIORITY_CLASS and HIGH_PRIORITY_CLASS
      
  <Side Effects>
    A new process is created
  
  <Returns>
    Process ID on success, None on failure.
  """
  # Create struct to hold process info
  process_info = _PROCESS_INFORMATION()
  process_info_addr = ctypes.pointer(process_info)
  
  # Determine what is the cmdline Parameter
  if not (cmdline == None):
    cmdline_param = unicode(cmdline)
  else:
    cmdline_param = None
  
  # For some reason, Windows Desktop uses the first part of the second parameter as the
  # Application... This is documented on MSDN under CreateProcess in the user comments
  # Create struct to hold window info
  window_info = _STARTUPINFO()
  window_info_addr = ctypes.pointer(window_info)
  cmdline_param = unicode(application) + " " + cmdline_param
  application = None
  
  # Lauch process, and save status
  status = _create_process(
    application, 
    cmdline_param,
    None,
    None,
    False,
    priority,
    None,
    None,
    window_info_addr,
    process_info_addr)
  
  # Did we succeed?
  if status:
    # Close handles that we don't need
    _close_handle(process_info.hProcess)
    _close_handle(process_info.hThread)
    
    # Return pid
    return process_info.dwProcessId
  else:
    return None
Example #3
0
    def initiator_transceive_bits(self, bits, numbits, paritybits = None):
        """Sends a series of bits, returning the number and bits sent back by the target"""
        if paritybits and len(paritybits) != len(bits):
            raise ValueError("Length of parity bits does not match length of bits")
        if len(bits) < ((numbits + 7) / 8):
            raise ValueError("Length of bits does not match the value passed in numbits")

        insize = min(((numbits + 7) / 8), MAX_FRAME_LEN)
        for i in range(insize):
            self._txbytes[i] = ord(bits[i])
            if paritybits:
                self._txpbytes[i] = ord(paritybits[i]) & 0x01

        parity = None
        if paritybits:
            parity = ctypes.pointer(self._txpbytes)

        rxbitlen = _size_t(0)

        result = _lib.nfc_initiator_transceive_bits(self._device,
                                                    ctypes.pointer(self._txbytes),
                                                    _size_t(numbits),
                                                    parity,
                                                    ctypes.pointer(self._rxbytes),
                                                    ctypes.byref(rxbitlen),
                                                    ctypes.pointer(self._rxpbytes))
        if not result:
            return None

        rxbytes = rxpbytes = ""
        for i in range(min(((rxbitlen.value + 7) / 8), MAX_FRAME_LEN)):
            rxbytes += chr(self._rxbytes[i])
            rxpbytes += chr(self._rxpbytes[i])

        return rxbytes, rxbitlen.value, rxpbytes
Example #4
0
    def convergence(self):
        """Compute L2 norms for convergence testing"""
        if self._library is None:
            self._load_library()
        if self._arg_grid is None:
            raise RuntimeError("""Convergence could not find grid argument!
You need to you run grid.execute() first!""")

        # Define OpesciConvergence struct
        class OpesciConvergence(Structure):
            _fields_ = [('%s_l2' % ccode(f.label), c_float)
                        for f in self.fields]

        # Generate the convergence argument
        arg_conv = OpesciConvergence()
        arg_conv.values = [c_float(0.) for f in self.fields]

        # Load opesci_convergence, define it's arguments and run
        print "Convergence:"
        opesci_convergence = self._library.opesci_convergence
        opesci_convergence.argtypes = [POINTER(self._arg_grid.__class__),
                                       POINTER(OpesciConvergence)]
        opesci_convergence(pointer(self._arg_grid), pointer(arg_conv))
        for field, _ in arg_conv._fields_:
            print "%s: %.10f" % (field, getattr(arg_conv, field))
Example #5
0
    def get_free_space(self, path):
        """
        Function Type : String
        """

        def get_readable_format(total):
            measures = ["B", "KB", "MB", "GB", "TB"]
            index = 0
            while index < len(measures) and total > 1024:
                total = float(total / 1024)
                index = index + 1

            return "%.2f %s" % (total, measures[index])

        total_bytes, free_bytes = ctypes.c_ulonglong(0), ctypes.c_ulonglong(0)
        if ctypes.windll.kernel32.GetDiskFreeSpaceExW(
            ctypes.c_wchar_p(path), None, ctypes.pointer(total_bytes), ctypes.pointer(free_bytes)
        ):
            free = get_readable_format(free_bytes.value)
            total = get_readable_format(total_bytes.value)
            ret_val = "%s of %s available" % (free, total)
        else:
            ret_val = "Could not determine"

        return ret_val
Example #6
0
def hash_data(buffer, alg, block_size=16*1024):
    if alg not in _calg_map:
        raise InvalidHashAlgorithm()
    
    block_size = int(block_size)
    if block_size <= 0:
        raise ValueError("'block_size' should be a positive integer")

    with _crypt_context() as hCryptProv:
        with _crypt_hash(hCryptProv, _calg_map[alg]) as hCryptHash:
            buffer_len = len(buffer)
            if block_size > buffer_len:
                block_size = buffer_len

            i = 0
            while i < buffer_len:
                count = block_size if (i + block_size <= buffer_len) else (buffer_len - i)
                if not CryptHashData(hCryptHash, _cast(buffer[i:i+count], PBYTE), DWORD(count), DWORD(0)):
                    raise WinError()
                i += count

            dwHashLen = DWORD(sizeof(DWORD))
            dwHashSize = DWORD()
            if not CryptGetHashParam(hCryptHash, HP_HASHSIZE, _cast(pointer(dwHashSize), PBYTE), pointer(dwHashLen), DWORD(0)):
                raise WinError()

            pbHashVal = (BYTE * dwHashSize.value)()
            dwHashLen.value = sizeof(pbHashVal)
            if not CryptGetHashParam(hCryptHash, HP_HASHVAL, pbHashVal, pointer(dwHashLen), DWORD(0)):
                raise WinError()

            return ''.join(map(lambda b: format(b, '02x'), bytes(pbHashVal)))
Example #7
0
    def mds_command(self, mds_spec, args, input_data):
        """
        :return 3-tuple of output status int, output status string, output data
        """

        cmdarr = (c_char_p * len(args))(*args)

        outbufp = pointer(pointer(c_char()))
        outbuflen = c_long()
        outsp = pointer(pointer(c_char()))
        outslen = c_long()

        ret = self.libcephfs.ceph_mds_command(self.cluster, c_char_p(mds_spec),
                                              cmdarr, len(args),
                                              c_char_p(input_data),
                                              len(input_data), outbufp,
                                              byref(outbuflen), outsp,
                                              byref(outslen))

        my_outbuf = outbufp.contents[:(outbuflen.value)]
        my_outs = outsp.contents[:(outslen.value)]
        if outbuflen.value:
            self.libcephfs.ceph_buffer_free(outbufp.contents)
        if outslen.value:
            self.libcephfs.ceph_buffer_free(outsp.contents)

        return (ret, my_outbuf, my_outs)
Example #8
0
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.drawables = []
        self.light_framebuffer = GLuint()
        self.light_texture = GLuint()

        self.w = window.width
        self.h = window.height

        # Create and activate the light framebuffer
        glGenFramebuffers(1, pointer(self.light_framebuffer))
        glBindFramebuffer(GL_FRAMEBUFFER, self.light_framebuffer)

        # Create a texture to render light into, activate it, initialize it and bind it as COLOR_ATTACHMENT0 on
        # the light framebuffer
        glGenTextures(1, pointer(self.light_texture))
        glBindTexture(GL_TEXTURE_2D, self.light_texture)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, None)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.light_texture, 0)

        # Deactivate the light texture
        glBindTexture(GL_TEXTURE_2D, 0)

        # Check the new framebuffer status
        status = glCheckFramebufferStatus(GL_FRAMEBUFFER)
        if status != GL_FRAMEBUFFER_COMPLETE:
            raise Exception("glCheckFramebufferStatus: ", status)

        # Deactivate the light framebuffer
        glBindFramebuffer(GL_FRAMEBUFFER, 0)
Example #9
0
    def __init__(self, **kwargs):
        '''Initialize the virtual screen.

        Possible keyword arguments:
        - `font`,
        - `options`,
        - `min_width`, `min_height` (in pixels),
        - `max_width`, `max_height` (in pixels),
        - `recommended_width`, `recommended_height` (in pixels),
        - `width`, `height` (in pixels),
        - `physical_width`, `physical_height` (in mm),
        - `dim_value`,
        - `bold_value`.
        '''
        settings = self._get_default_settings()
        for k, v in kwargs.items():
            setattr(settings, k, v)
        context = self._context = aa_init(ctypes.pointer(aa_mem_d), ctypes.pointer(settings), None)
        if context is None:
            raise ScreenInitializationFailed
        self._render_width = aa_scrwidth(context)
        self._render_height = aa_scrheight(context)
        self._virtual_width = aa_imgwidth(context)
        self._virtual_height = aa_imgheight(context)
        self._framebuffer = aa_image(context)
Example #10
0
	def put(self, txn, dbi, key, value, flags):
		"""Put item into database."""
		if txn is None or dbi is None:
			raise InvalidHandleError("put")
		err = self._lib.mdb_put(txn, dbi, ctypes.pointer(key), ctypes.pointer(value), flags)
		if err != 0:
			raise APIError(err, self.strerror(err))
Example #11
0
	def delete(self, txn, dbi, key, value):
		"""Delete item from database."""
		if txn is None or dbi is None:
			raise InvalidHandleError("delete")
		err = self._lib.mdb_del(txn, dbi, ctypes.pointer(key), None if value is None else ctypes.pointer(value))
		if err != 0:
			raise APIError(err, self.strerror(err))
Example #12
0
 def _nl_getsockname(descriptor):
     addr = SOCKADDR_NL(0, 0, 0, 0)
     len = ctypes.c_int(ctypes.sizeof(addr));
     libc.getsockname(descriptor.fileno(),
                      ctypes.pointer(addr),
                      ctypes.pointer(len))
     return addr.nl_pid, addr.nl_groups;
Example #13
0
def ListProcessModules( ProcessID ):
    hModuleSnap = c_void_p(0)
    me32 = MODULEENTRY32()
    me32.dwSize = sizeof( MODULEENTRY32 )
    hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, ProcessID )

    ret = Module32First( hModuleSnap, pointer(me32) )
    if ret == 0 :
        print('ListProcessModules() Error on Module32First[%d]' % GetLastError())
        CloseHandle( hModuleSnap )
        return False

    while ret :
        print( "   MODULE NAME:     %s"%             me32.szModule )
        print ("   executable     = %s"%             me32.szExePath)
        print ("   process ID     = 0x%08X"%         me32.th32ProcessID)
        print ("   ref count (g)  =     0x%04X"%     me32.GlblcntUsage)
        print ("   ref count (p)  =     0x%04X"%     me32.ProccntUsage)
        print ("   base address   = 0x%08X"%         me32.modBaseAddr)
        print ("   base size      = %d"%             me32.modBaseSize)

        ret = Module32Next( hModuleSnap , pointer(me32) )

    CloseHandle( hModuleSnap )
    return True
def _get_bounds(handle, bounds_fn, interleaved):
    pp_mins = ctypes.pointer(ctypes.c_double())
    pp_maxs = ctypes.pointer(ctypes.c_double())
    dimension = ctypes.c_uint32(0)

    bounds_fn(handle,
            ctypes.byref(pp_mins),
            ctypes.byref(pp_maxs),
            ctypes.byref(dimension))
    if (dimension.value == 0): return None

    mins = ctypes.cast(pp_mins,ctypes.POINTER(ctypes.c_double \
                                                      * dimension.value))
    maxs = ctypes.cast(pp_maxs,ctypes.POINTER(ctypes.c_double \
                                                      * dimension.value))

    results = [mins.contents[i] for i in range(dimension.value)]
    results += [maxs.contents[i] for i in range(dimension.value)]

    p_mins = ctypes.cast(mins,ctypes.POINTER(ctypes.c_double))
    p_maxs = ctypes.cast(maxs,ctypes.POINTER(ctypes.c_double))
    core.rt.Index_Free(ctypes.cast(p_mins, ctypes.POINTER(ctypes.c_void_p)))
    core.rt.Index_Free(ctypes.cast(p_maxs, ctypes.POINTER(ctypes.c_void_p)))
    if interleaved: # they want bbox order.
        return results
    return Index.deinterleave(results)
Example #15
0
	def SetValue(self, value):
		# set object type
		otype = None
		size = 8
		if type(value) == str:
			otype = ASN_OCTET_STR
			size = len(value)
			value = ctypes.c_char_p(value)
		elif type(value) == int:
			otype = ASN_INTEGER
			value = ctypes.pointer(ctypes.c_int(value))
		elif type(value) == float:
			otype = ASN_APP_FLOAT
			value = ctypes.pointer(ctypes.c_float(value))
		elif type(value) == SnmpIpAddress:
			otype = ASN_IPADDRESS
			size = 4
			value = ctypes.c_char_p(socket.inet_aton(value))
		elif type(value) == SnmpCounter32:
			otype = ASN_COUNTER32
			value = ctypes.pointer(ctypes.c_uint(value))
		elif type(value) == SnmpGauge32:
			otype = ASN_UNSIGNED
			value = ctypes.pointer(ctypes.c_uint(value))
		axl.snmp_set_var_typed_value(self.__request.requestvb, otype, ctypes.cast(value, ctypes.POINTER(ctypes.c_ubyte)), size)
		self.value = value
Example #16
0
File: pam.py Project: sveinou/DF
def authenticate(username, password, service='login'):
    """Returns True if the given username and password authenticate for the
    given service.  Returns False otherwise

    ``username``: the username to authenticate

    ``password``: the password in plain text

    ``service``: the PAM service to authenticate against.
                 Defaults to 'login'"""
    @CONV_FUNC
    def my_conv(n_messages, messages, p_response, app_data):
        """Simple conversation function that responds to any
        prompt where the echo is off with the supplied password"""
        # Create an array of n_messages response objects
        addr = CALLOC(n_messages, sizeof(PamResponse))
        p_response[0] = cast(addr, POINTER(PamResponse))
        for i in range(n_messages):
            if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
                pw_copy = STRDUP(str(password))
                p_response.contents[i].resp = cast(pw_copy, c_char_p)
                p_response.contents[i].resp_retcode = 0
        return 0

    handle = PamHandle()
    conv = PamConv(my_conv, 0)
    retval = PAM_START(service, username, pointer(conv), pointer(handle))

    if retval != 0:
        # TODO: This is not an authentication error, something
        # has gone wrong starting up PAM
        return False

    retval = PAM_AUTHENTICATE(handle, 0)
    return retval == 0
Example #17
0
def get_bucket(uhash, pieces, first_bucket_vector, second_bucket_vector):
    h_index = np.uint64(first_bucket_vector[0]) + np.uint64(second_bucket_vector[0 + 2])
    if h_index >= const.prime_default:
        h_index -= const.prime_default
    assert(h_index < const.prime_default)
    h_index = np.uint32(h_index)
    h_index = h_index % uhash.table_size

    control = np.uint64(first_bucket_vector[1]) + np.uint64(second_bucket_vector[1 + 2])
    if control >= const.prime_default:
        control -= const.prime_default
    assert(control < const.prime_default)
    control = np.uint32(control)
    
    if uhash.t == 2:
        index_hybrid = uhash.hybrid_hash_table[h_index]

        while index_hybrid:
            if index_hybrid.control_value == control:
                index_hybrid = C.pointer(index_hybrid)[1]
                return index_hybrid
            else:
                index_hybrid = C.pointer(index_hybrid)[1]
                if index_hybrid.point.is_last_bucket:
                    return None
                l = index_hybrid.point.bucket_length
                index_hybrid = C.pointer(index_hybrid)[l]
        return None
Example #18
0
def vasco_verify(data, params, password, challenge="\0" * 16):
    res = Vasco_DLL.AAL2VerifyPassword(pointer(data),
                                           pointer(params),
                                           c_char_p(password),
                                           c_char_p(challenge)
                                          )
    return (res, data)
Example #19
0
 def getVelocityParameters(self):
     minimumVelocity = c_float()
     acceleration = c_float()
     maximumVelocity = c_float()
     self.aptdll.MOT_GetVelParams(self.SerialNum, pointer(minimumVelocity), pointer(acceleration), pointer(maximumVelocity))
     velocityParameters = [minimumVelocity.value, acceleration.value, maximumVelocity.value]
     return velocityParameters
Example #20
0
def vasco_dpxinit(filename="demovdp.dpx", transportkey=None):
    '''
    This function returns
     - error code
     - filehandle (TDPXHandle)
     - application count
     - application names
     - token counts
    '''
    if not transportkey:
        transportkey = "1" * 32

    c_filename = c_char_p(filename)
    c_transportkey = c_char_p(transportkey)
    # string with 97 bytes
    appl_names = "." * 97
    p_names = c_char_p(appl_names)

    fh = TDPXHandle()
    p_fh = pointer(fh)

    appl_count = c_int(0)
    p_acount = pointer(appl_count)

    token_count = c_int(0)
    p_tcount = pointer(token_count)

    res = Vasco_DLL.AAL2DPXInit(p_fh,
                            c_filename,
                            c_transportkey,
                            p_acount,
                            p_names,
                            p_tcount)

    return (res, fh, appl_count, appl_names, token_count)
Example #21
0
def vasco_genpassword(data, params, challenge="\0" * 16):
    password = "******" * 41
    res = Vasco_DLL.AAL2GenPassword(pointer(data),
                                     pointer(params),
                                     c_char_p(password),
                                     c_char_p(challenge))
    return (res, password)
Example #22
0
def ant_colony_TSP_run(cities, params):
    
    dimension = len(cities[0])
    
    cities_coord = ant_colony_TSP_cities()
    cities_coord.size = ct.c_uint(len(cities) * dimension)
    cities_coord.dimension = ct.c_uint(dimension)
    
    cities_coord.data = (ct.c_double * cities_coord.size)();
    for i in range(0, cities_coord.size):
        cities_coord.data[i] =cities[i // dimension][i % dimension]
    
    cities_coord = ct.pointer(cities_coord);


    algorithm_params = ant_colony_TSP_params()
    algorithm_params.q          = ct.c_double(params.q)
    algorithm_params.ro         = ct.c_double(params.ro)
    algorithm_params.alpha      = ct.c_double(params.alpha)
    algorithm_params.beta       = ct.c_double(params.beta)
    algorithm_params.gamma      = ct.c_double(params.gamma)
    algorithm_params.qinitial_pheramone         = ct.c_double(params.qinitial_pheramone)
    algorithm_params.iterations                 = ct.c_uint(params.iterations)
    algorithm_params.count_ants_in_iteration    = ct.c_uint(params.count_ants_in_iteration)
    
    algorithm_params = ct.pointer(algorithm_params)
    
    
    ccore = ct.cdll.LoadLibrary(PATH_DLL_CCORE_WIN64)
    result = ccore.ant_colony_TSP(cities_coord, algorithm_params)
    
    result = ct.cast(result, ct.POINTER(ant_colony_TSP_result))[0]
    #result = result[0]    
    
    return result
Example #23
0
 def get_3d_attributes(self):
  """Retrieves the 3D attributes of a sample, stream, or MOD music channel with 3D functionality."""
  answer = dict(mode=c_ulong(), min=c_float(), max=c_float(), iangle=c_ulong(), oangle=c_ulong(), outvol=c_float())
  bass_call(BASS_ChannelGet3DAttributes, self.handle, pointer(answer['mode']), pointer(answer['min']), pointer(answer['max']), pointer(answer['iangle']), pointer(answer['oangle']), pointer(answer['outvol']))
  for k in answer:
   answer[k] = answer[k].value()
  return answer
Example #24
0
    def up(self, key, override=None):
        '''
        Releases the given key
        '''
        key_code = self._get_scancode(key)
        
        if override:
            key_code = override

        if key in self._extended_scancodes:
            is_extended = KEYEVENTF_EXTENDEDKEY
        else:
            is_extended = 0
        input_arr = Input * 1
        extra = c_ulong(0)
        ii_ = InputUnion()
        ii_.keyb_inp = KeyBdInput(0,
                                  key_code,
                                  is_extended + 
                                    KEYEVENTF_KEYUP + 
                                    KEYEVENTF_SCANCODE,
                                  0,
                                  pointer(extra))

        inputs = input_arr(( 1, ii_ ))
        windll.user32.SendInput(1, pointer(inputs), sizeof(inputs[0]))
Example #25
0
    def down(self, key, override=None):
        '''
        Holds down the given key
        '''
        if key != key.lower() and len(key) == 1:
            use_shift = True
            self.down('left shift')
        else:
            use_shift = False

        key_code = self._get_scancode(key)
        
        if override:
            key_code = override

        if key in self._extended_scancodes:
            is_extended = KEYEVENTF_EXTENDEDKEY
        else:
            is_extended = 0
            
        input_arr = Input * 1
        extra = c_ulong(0)
        ii_ = InputUnion()
        ii_.keyb_inp = KeyBdInput(0,
                                  key_code,
                                  is_extended + KEYEVENTF_SCANCODE,
                                  0,
                                  pointer(extra))
        inputs = input_arr( ( 1, ii_ ) )
        windll.user32.SendInput(1, pointer(inputs), sizeof(inputs[0]))
    
        if use_shift:
            self.up('left shift')
Example #26
0
def ReleaseKey(hexKeyCode):
    if hexKeyCode != 0x0 :
        extra = ctypes.c_ulong(0)
        ii_ = Input_I()
        ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
        x = Input( ctypes.c_ulong(1), ii_ )
        ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
Example #27
0
  def from_python(self, x):
    if not isinstance(x, np.ndarray):
      print "Warning: Copying %s into Parakeet, will never get deleted" % \
          (type(x))
      x = np.asarray(x)
      self._store_forever.append(x)

    
    nelts = reduce(lambda x,y: x*y, x.shape)
    elt_size = x.dtype.itemsize
    total_bytes = nelts * elt_size
    
    try:
      ptr, buffer_length = buffer_info(x.data, self.ptr_t.ctypes_repr)
      assert total_bytes == buffer_length, \
        "Shape %s has %d elements of size %d (total = %d) but buffer has %d bytes" % \
        (x.shape, nelts, elt_size, total_bytes, buffer_length)
    
    except:
      print "Warning: Failed to get NumPy buffer for array with shape %s" % \
        (x.shape,)
      ptr = x.ctypes.data_as(self.ptr_t.ctypes_repr)
    
    self._seen_ptr.add(ctypes.addressof(ptr))
    ctypes_shape = self.shape_t.from_python(x.shape)
    strides_in_elts = tuple([s / elt_size for s in x.strides])
    ctypes_strides = self.strides_t.from_python(strides_in_elts)
    return self.ctypes_repr(ptr, ctypes.pointer(ctypes_shape),
                            ctypes.pointer(ctypes_strides), 0, nelts)
def _get_disk_usage(path=None):
  """
  returns a named tuple that contains the total, used, and free disk space
  in bytes. Windows implementation
  """
  import string
  import ctypes

  used = 0
  total = 0
  free = 0
  drives = []
  bitmask = ctypes.windll.kernel32.GetLogicalDrives()
  for letter in string.uppercase:
    if bitmask & 1:
      drives.append(letter)
    bitmask >>= 1
  for drive in drives:
    free_bytes = ctypes.c_ulonglong(0)
    total_bytes = ctypes.c_ulonglong(0)
    ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(drive + ":\\"),
                                               None, ctypes.pointer(total_bytes),
                                               ctypes.pointer(free_bytes))
    total += total_bytes.value
    free += free_bytes.value
    used += total_bytes.value - free_bytes.value

  return DiskInfo(total=total, used=used, free=free, path=None)
def make_input_objects( l_keys ):

    p_ExtraInfo_0 = ct.pointer(ct.c_ulong(0))

    l_inputs = [ ]
    for n_key, n_updown in l_keys:
        ki = cls_KeyBdInput( n_key, 0, n_updown, 0, p_ExtraInfo_0 )
        ii = cls_Input_I()
        ii.ki = ki
        l_inputs.append( ii )

    n_inputs = len(l_inputs)

    l_inputs_2=[]
    for ndx in range( 0, n_inputs ):
        s2 = "(1, l_inputs[%s])" % ndx
        l_inputs_2.append(s2)
    s_inputs = ', '.join(l_inputs_2)


    cls_input_array = cls_Input * n_inputs
    o_input_array = eval( "cls_input_array( %s )" % s_inputs )

    p_input_array = ct.pointer( o_input_array )
    n_size_0 = ct.sizeof( o_input_array[0] )

    # these are the args for user32.SendInput()
    return ( n_inputs, p_input_array, n_size_0 )

    '''It is interesting that o_input_array has gone out of scope
Example #30
0
    def run(self):

        libc = ctypes.cdll.LoadLibrary("libc.so.7")
        omask = (ctypes.c_uint32 * 4)(0, 0, 0, 0)
        mask = (ctypes.c_uint32 * 4)(0, 0, 0, 0)
        pmask = ctypes.pointer(mask)
        pomask = ctypes.pointer(omask)
        libc.sigprocmask(SIG_SETMASK, pmask, pomask)

        proc = subprocess.Popen(
            [
                "dd",
                "if=/dev/random",
                "of=%s" % self._dev,
                "bs=1m",
            ],
            stdout=subprocess.PIPE,
            stderr=self._stderr,
        )

        self._pid = proc.pid

        proc.communicate()
        self._exit = proc.returncode

        libc.sigprocmask(SIG_SETMASK, pomask, None)
Example #31
0
def install():
    netAppPath = '%s/Autodesk/Maya/%s.%s' %(ROOT_APP_PATH['network'], MAJV, MINV)
    locAppPath = '%s/Autodesk/Maya/%s.%s' %(ROOT_APP_PATH['local'], MAJV, MINV)

    if os.path.exists(netAppPath):
        if not os.path.exists(locAppPath):
            appsize = 0
            for item in os.walk(netAppPath):
                for f in item[2]:
                    try:
                        appsize = appsize + os.path.getsize(os.path.join(item[0], f))
                    except:
                        print("error with file:  " + os.path.join(item[0], f))

            freebytes = ctypes.c_ulonglong(0)
            ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p('C:\\'), None, None, ctypes.pointer(freebytes))
            
            if float(appsize) < freebytes:            
                print "Installing Maya %s.%s from the network. Please wait..." %(MAJV, MINV)
                shutil.copytree(netAppPath, locAppPath)
                print "Done!"
            else:
                print "Not enough disk space! Alert your administrator or run with --network flag."
                return 1
        else:
            print "%s already exists on your computer!" %(locAppPath)
            return 1
    else:
        print "%s does not exist on the app server!" %(netAppPath)
        return 1
Example #32
0
 def set_pubkey(self, key):
     self.mb = ctypes.create_string_buffer(key)
     return ssl.o2i_ECPublicKey(ctypes.byref(self.k),
                                ctypes.byref(ctypes.pointer(self.mb)),
                                len(key))
Example #33
0
 def set_privkey(self, key):
     self.mb = ctypes.create_string_buffer(key)
     return ssl.d2i_ECPrivateKey(ctypes.byref(self.k),
                                 ctypes.byref(ctypes.pointer(self.mb)),
                                 len(key))
Example #34
0
def ReleaseKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
Example #35
0
    def __init__(self, handle, size = 4096): #4096): #16384):
        "Allocate the memory"
        self.memAddress = 0
        self.size = size
        self.process = 0
        
        if handle == 0xffffffff80000000:
            raise Exception('Incorrect handle: ' + str(handle))

        self._as_parameter_ = self.memAddress

        if sysinfo.is_x64_Python():
            process_id = ctypes.c_ulonglong()
        else:
            process_id = ctypes.c_ulong()
        win32functions.GetWindowThreadProcessId(
            handle, ctypes.byref(process_id))
        if not process_id.value:
            raise AccessDenied(
                str(ctypes.WinError()) + " Cannot get process ID from handle.")

        self.process = win32functions.OpenProcess(
                win32defines.PROCESS_VM_OPERATION |
                win32defines.PROCESS_VM_READ |
                win32defines.PROCESS_VM_WRITE,
            0,
            process_id)

        if not self.process:
            raise AccessDenied(
                str(ctypes.WinError()) + "process: %d",
                process_id.value)

        self.memAddress = win32functions.VirtualAllocEx(
            ctypes.c_void_p(self.process),	# remote process
            ctypes.c_void_p(0),				# let Valloc decide where
            win32structures.ULONG_PTR(self.size + 4),# how much to allocate
                win32defines.MEM_RESERVE |
                win32defines.MEM_COMMIT, # allocation type
            win32defines.PAGE_READWRITE  # protection
            )
        if hasattr(self.memAddress, 'value'):
            self.memAddress = self.memAddress.value

        if self.memAddress == 0:
            raise ctypes.WinError()
        
        if hex(self.memAddress) == '0xffffffff80000000' or hex(self.memAddress).upper() == '0xFFFFFFFF00000000':
            raise Exception('Incorrect allocation: ' + hex(self.memAddress))

        self._as_parameter_ = self.memAddress
        
        # write guard signature at the end of memory block
        signature = win32structures.LONG(0x66666666)
        ret = win32functions.WriteProcessMemory(
            ctypes.c_void_p(self.process),
            ctypes.c_void_p(self.memAddress + self.size),
            ctypes.pointer(signature),
            win32structures.ULONG_PTR(4),
            win32structures.ULONG_PTR(0));
        if ret == 0:
            print('================== Error: Failed to write guard signature: address = ', self.memAddress, ', size = ', self.size)
            last_error = win32api.GetLastError()
            print('LastError = ', last_error, ': ', win32api.FormatMessage(last_error).rstrip())
            sys.stdout.flush()
Example #36
0
def read_ogg_opus(ogg_file):
    error = ctypes.c_int()
    ogg_file_buffer = ogg_file.getbuffer()
    ubyte_array = ctypes.c_ubyte * len(ogg_file_buffer)
    opusfile = pyogg.opus.op_open_memory(
        ubyte_array.from_buffer(ogg_file_buffer),
        len(ogg_file_buffer),
        ctypes.pointer(error)
    )

    if error.value != 0:
        raise ValueError(
            ("Ogg/Opus buffer could not be read."
             "Error code: {}").format(error.value)
        )

    channel_count = pyogg.opus.op_channel_count(opusfile, -1)
    sample_rate = 48000 # opus files are always 48kHz
    sample_width = 2 # always 16-bit
    audio_format = AudioFormat(sample_rate, channel_count, sample_width)

    # Allocate sufficient memory to store the entire PCM
    pcm_size = pyogg.opus.op_pcm_total(opusfile, -1)
    Buf = pyogg.opus.opus_int16*(pcm_size*channel_count)
    buf = Buf()

    # Create a pointer to the newly allocated memory.  It
    # seems we can only do pointer arithmetic on void
    # pointers.  See
    # https://mattgwwalker.wordpress.com/2020/05/30/pointer-manipulation-in-python/
    buf_ptr = ctypes.cast(
        ctypes.pointer(buf),
        ctypes.c_void_p
    )
    assert buf_ptr.value is not None # for mypy
    buf_ptr_zero = buf_ptr.value

    #: Bytes per sample
    bytes_per_sample = ctypes.sizeof(pyogg.opus.opus_int16)

    # Read through the entire file, copying the PCM into the
    # buffer
    samples = 0
    while True:
        # Calculate remaining buffer size
        remaining_buffer = (
            len(buf) # int
            - (buf_ptr.value - buf_ptr_zero) // bytes_per_sample
        )

        # Convert buffer pointer to the desired type
        ptr = ctypes.cast(
            buf_ptr,
            ctypes.POINTER(pyogg.opus.opus_int16)
        )

        # Read the next section of PCM
        ns = pyogg.opus.op_read(
            opusfile,
            ptr,
            remaining_buffer,
            pyogg.ogg.c_int_p()
        )

        # Check for errors
        if ns < 0:
            raise ValueError(
                "Error while reading OggOpus buffer. "+
                "Error code: {}".format(ns)
            )

        # Increment the pointer
        buf_ptr.value += (
            ns
            * bytes_per_sample
            * channel_count
        )
        assert buf_ptr.value is not None # for mypy

        samples += ns

        # Check if we've finished
        if ns == 0:
            break

    # Close the open file
    pyogg.opus.op_free(opusfile)

    # Cast buffer to a one-dimensional array of chars
    #: Raw PCM data from audio file.
    CharBuffer = ctypes.c_byte * (bytes_per_sample * channel_count * pcm_size)
    audio_data = CharBuffer.from_buffer(buf)

    return audio_format, audio_data
def _get_ctypes_data():
    value = ctypes.c_double(2.0)
    return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp)
Example #38
0
File: table.py Project: u332744/bcc
 def __delitem__(self, key):
     key_p = ct.pointer(key)
     res = lib.bpf_delete_elem(self.map_fd, ct.cast(key_p, ct.c_void_p))
     if res < 0:
         raise KeyError
Example #39
0
import ctypes

shellcode = (
);
#Dont Add any '(' symbol before this line  !!!!!!
ptr = ctypes.windll.kernel32.VirtualAlloc(0,4096,ctypes.c_int(0x1000),ctypes.c_int(0x40))

b = bytearray()

b.extend(map(ord, shellcode))

buf = (ctypes.c_char * len(shellcode)).from_buffer(b)

ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr),
					buf,
					ctypes.c_int(len(shellcode)))

ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),
					ctypes.c_int(0),
					ctypes.c_int(ptr),
					ctypes.c_int(0),
					ctypes.c_int(0),
					ctypes.pointer(ctypes.c_int(0)))

ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))
Example #40
0
def run_shellcode(shellcode):
    # Methods used are heavily inspired by the following:
    #   http://hacktracking.blogspot.com/2015/05/execute-shellcode-in-python.html
    #   http://www.debasish.in/2012/04/execute-shellcode-using-python.html

    sbytes = read_in_bytes(shellcode, False)

    print("Shellcode length: {:d}".format(sbytes[2]))

    if os.name == 'posix':

        shellcode = bytes(sbytes[1])  # convert shellcode into a bytes
        libc = CDLL('libc.so.6')  # implement C functions (duh)
        sc = c_char_p(shellcode)  # character pointer (NUL terminated)
        size = len(shellcode)  # size of the shellcode executing
        addr = c_void_p(libc.valloc(
            size))  # allocate bytes and return pointer to allocated memory
        memmove(addr, sc, size)  # copy bytes to allocated memory destination
        libc.mprotect(addr, size, 0x7)  # change access protections
        run = cast(addr, CFUNCTYPE(c_void_p))  # calling convention
        run()  # run the shellcode

    else:

        shellcode = bytearray(sbytes[1])

        # LPVOID WINAPI VirtualAlloc(
        #   __in_opt  LPVOID lpAddress,         // Address of the region to allocate. If this parameter is NULL, the system determines where to allocate the region.
        #   __in      SIZE_T dwSize,            // Size of the region in bytes. Here we put the size of the shellcode
        #   __in      DWORD flAllocationType,   // The type of memory allocation, flags 0x1000 (MEMCOMMIT) and 0x2000 (MEMRESERVE) to both reserve and commit memory
        #   __in      DWORD flProtect           // Enables RWX to the committed region of pages
        # );
        ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
                                                  ctypes.c_int(len(shellcode)),
                                                  ctypes.c_int(0x3000),
                                                  ctypes.c_int(0x40))
        # BOOL WINAPI VirtualLock(
        #   _In_ LPVOID lpAddress,  // A pointer to the base address of the region of pages to be locked
        #   _In_ SIZE_T dwSize      // The size of the region to be locked, in bytes.
        # );
        buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
        # VOID RtlMoveMemory(
        #   _Out_       VOID UNALIGNED *Destination,    // A pointer to the destination memory block to copy the bytes to.
        #   _In_  const VOID UNALIGNED *Source,         // A pointer to the source memory block to copy the bytes from.
        #   _In_        SIZE_T         Length           // The number of bytes to copy from the source to the destination.
        # );
        ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf,
                                             ctypes.c_int(len(shellcode)))
        # HANDLE WINAPI CreateThread(
        #   _In_opt_  LPSECURITY_ATTRIBUTES  lpThreadAttributes,    // If lpThreadAttributes is NULL, the thread gets a default security descriptor.
        #   _In_      SIZE_T                 dwStackSize,           // If this parameter is zero, the new thread uses the default size for the executable.
        #   _In_      LPTHREAD_START_ROUTINE lpStartAddress,        // A pointer to the application-defined function to be executed by the thread.
        #   _In_opt_  LPVOID                 lpParameter,           // optional (A pointer to a variable to be passed to the thread)
        #   _In_      DWORD                  dwCreationFlags,       // Run the thread immediately after creation.
        #   _Out_opt_ LPDWORD                lpThreadId             // NULL, so the thread identifier is not returned.
        # );
        ht = ctypes.windll.kernel32.CreateThread(
            ctypes.c_int(0), ctypes.c_int(0), ctypes.c_int(ptr),
            ctypes.c_int(0), ctypes.c_int(0), ctypes.pointer(ctypes.c_int(0)))
        # Waits until the specified object is in the signaled state or the time-out interval elapses
        ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),
                                                   ctypes.c_int(-1))

    sys.exit()
Example #41
0
TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY)
TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY
                    | TOKEN_DUPLICATE | TOKEN_IMPERSONATION | TOKEN_QUERY
                    | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES
                    | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT
                    | TOKEN_ADJUST_SESSIONID)

dwDesiredAccess = PROCESS_ALL_ACCESS
bInheritHandle = False
handle = k_handle.OpenProcess(dwDesiredAccess, bInheritHandle, lpdwProcessId)
print(lpdwProcessId)
error2 = k_handle.GetLastError()
if error2 != 0:
    print(error2)
if handle <= 0:
    print("handle not created")
else:
    print(handle)

ProcessHandle = handle
DesiredAccess = TOKEN_ALL_ACCESS
TokenHandle = ctypes.c_void_p()

response = a_handle.OpenProcessToken(ProcessHandle, DesiredAccess,
                                     ctypes.pointer(TokenHandle))

if response == 0:
    print("error code {0}".format(k_handle.GetLastError()))
else:
    print(response)
Example #42
0
File: table.py Project: u332744/bcc
 def __delitem__(self, key):
     key = self._normalize_key(key)
     key_p = ct.pointer(key)
     res = lib.bpf_delete_elem(self.map_fd, ct.cast(key_p, ct.c_void_p))
     if res < 0:
         raise Exception("Could not delete item")
Example #43
0
 def get_privkey(self):
     size = ssl.i2d_ECPrivateKey(self.k, 0)
     mb_pri = ctypes.create_string_buffer(size)
     ssl.i2d_ECPrivateKey(self.k, ctypes.byref(ctypes.pointer(mb_pri)))
     return mb_pri.raw
 def get_public_key(self, encode='hex'):
     size = ssl.i2o_ECPublicKey(self.eckey, 0)
     mb = ctypes.create_string_buffer(size)
     ssl.i2o_ECPublicKey(self.eckey, ctypes.byref(ctypes.pointer(mb)))
     return mb.raw.encode('hex') if encode == 'hex' else mb.raw
Example #45
0
app: windows_explorer
app: windows_file_browser
"""

user_path = os.path.expanduser("~")
directories_to_remap = {}
directories_to_exclude = {}

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"))):

        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"),
Example #46
0
 def get_pubkey(self):
     size = ssl.i2o_ECPublicKey(self.k, 0)
     mb = ctypes.create_string_buffer(size)
     ssl.i2o_ECPublicKey(self.k, ctypes.byref(ctypes.pointer(mb)))
     return mb.raw
Example #47
0
def adsSyncReadReqEx2(port, address, index_group, index_offset, data_type):
    # type: (int, AmsAddr, int, int, Type) -> Any
    """Read data synchronous from an ADS-device.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param Type data_type: type of the data given to the PLC, according to
        PLCTYPE constants
    :rtype: data_type
    :return: value: **value**

    """
    sync_read_request = _adsDLL.AdsSyncReadReqEx2

    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
    index_group_c = ctypes.c_ulong(index_group)
    index_offset_c = ctypes.c_ulong(index_offset)

    if data_type == PLCTYPE_STRING:
        data = (STRING_BUFFER * PLCTYPE_STRING)()
    else:
        data = data_type()

    data_pointer = ctypes.pointer(data)
    data_length = ctypes.c_ulong(ctypes.sizeof(data))

    bytes_read = ctypes.c_ulong()
    bytes_read_pointer = ctypes.pointer(bytes_read)

    error_code = sync_read_request(
        port,
        ams_address_pointer,
        index_group_c,
        index_offset_c,
        data_length,
        data_pointer,
        bytes_read_pointer,
    )

    if error_code:
        raise ADSError(error_code)

    # If we're reading a value of predetermined size (anything but a string),
    # validate that the correct number of bytes were read
    if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:
        raise RuntimeError(
            "Insufficient data (expected {0} bytes, {1} were read).".format(
                data_length.value, bytes_read.value))

    if data_type == PLCTYPE_STRING:
        return data.value.decode("utf-8")

    if type(data_type).__name__ == "PyCArrayType":
        return [i for i in data]

    if hasattr(data, "value"):
        return data.value

    return data
Example #48
0
 def removeBackgroundEffect(self, hWnd):
     """ 移除背景特效效果 """
     self.accentPolicy.AccentState = ACCENT_STATE.ACCENT_DISABLED.value[0]
     self.SetWindowCompositionAttribute(int(hWnd),
                                        pointer(self.winCompAttrData))
Example #49
0
ED_GYROX=17
ED_GYROY=18
ED_TIMESTAMP=19
ED_ES_TIMESTAMP=20
ED_FUNC_ID=21
ED_FUNC_VALUE=22
ED_MARKER=23
ED_SYNC_SIGNAL=24

targetChannelList = [ED_COUNTER,ED_AF3, ED_F7, ED_F3, ED_FC5, ED_T7,ED_P7, ED_O1, ED_O2, ED_P8, ED_T8,ED_FC6, ED_F4, ED_F8, ED_AF4, ED_GYROX, ED_GYROY, ED_TIMESTAMP, ED_FUNC_ID, ED_FUNC_VALUE, ED_MARKER, ED_SYNC_SIGNAL]
eEvent      = libEDK.EE_EmoEngineEventCreate()
eState      = libEDK.EE_EmoStateCreate()
userID            = c_uint(0)
nSamples   = c_uint(0)
nSam       = c_uint(0)
nSamplesTaken  = pointer(nSamples)
#da = zeros(128,double)
data     = pointer(c_double(0))
user                    = pointer(userID)
composerPort          = c_uint(1726)
secs      = c_float(1)
datarate    = c_uint(0)
readytocollect    = False
option      = c_int(0)
state     = c_int(0)

input=''
print "==================================================================="
print "Example to show how to log EEG Data from EmoEngine/EmoComposer."
print "==================================================================="
print "Press '1' to start and connect to the EmoEngine                    "
Example #50
0
def adsSyncAddDeviceNotificationReqEx(port,
                                      adr,
                                      data_name,
                                      pNoteAttrib,
                                      callback,
                                      user_handle=None):
    # type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int]
    """Add a device notification.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr adr: local or remote AmsAddr
    :param string data_name: PLC storage address
    :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes
    :param callback: Callback function to handle notification
    :param user_handle: User Handle
    :rtype: (int, int)
    :returns: notification handle, user handle

    """
    global callback_store

    if NOTEFUNC is None:
        raise TypeError("Callback function type can't be None")

    adsSyncAddDeviceNotificationReqFct = (
        _adsDLL.AdsSyncAddDeviceNotificationReqEx)

    pAmsAddr = ctypes.pointer(adr.amsAddrStruct())
    hnl = adsSyncReadWriteReqEx2(
        port,
        adr,
        ADSIGRP_SYM_HNDBYNAME,
        0x0,
        PLCTYPE_UDINT,
        data_name,
        PLCTYPE_STRING,
    )

    nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)
    nIndexOffset = ctypes.c_ulong(hnl)
    attrib = pNoteAttrib.notificationAttribStruct()
    pNotification = ctypes.c_ulong()

    nHUser = ctypes.c_ulong(hnl)
    if user_handle is not None:
        nHUser = ctypes.c_ulong(user_handle)

    adsSyncAddDeviceNotificationReqFct.argtypes = [
        ctypes.c_ulong,
        ctypes.POINTER(SAmsAddr),
        ctypes.c_ulong,
        ctypes.c_ulong,
        ctypes.POINTER(SAdsNotificationAttrib),
        NOTEFUNC,
        ctypes.c_ulong,
        ctypes.POINTER(ctypes.c_ulong),
    ]
    adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long

    def wrapper(addr, notification, user):
        # type: (AmsAddr, SAdsNotificationHeader, int) -> Callable[[SAdsNotificationHeader, str], None]
        return callback(notification, data_name)

    c_callback = NOTEFUNC(wrapper)
    err_code = adsSyncAddDeviceNotificationReqFct(
        port,
        pAmsAddr,
        nIndexGroup,
        nIndexOffset,
        ctypes.byref(attrib),
        c_callback,
        nHUser,
        ctypes.byref(pNotification),
    )

    if err_code:
        raise ADSError(err_code)
    callback_store[pNotification.value] = c_callback
    return (pNotification.value, hnl)
Example #51
0
def getRunningProcessExePathByName_win32(name):
    from ctypes import windll, POINTER, pointer, Structure, sizeof
    from ctypes import c_long, c_int, c_uint, c_char, c_ubyte, c_char_p, c_void_p

    class PROCESSENTRY32(Structure):
        _fields_ = [('dwSize', c_uint), ('cntUsage', c_uint),
                    ('th32ProcessID', c_uint), ('th32DefaultHeapID', c_uint),
                    ('th32ModuleID', c_uint), ('cntThreads', c_uint),
                    ('th32ParentProcessID', c_uint),
                    ('pcPriClassBase', c_long), ('dwFlags', c_uint),
                    ('szExeFile', c_char * 260), ('th32MemoryBase', c_long),
                    ('th32AccessKey', c_long)]

    class MODULEENTRY32(Structure):
        _fields_ = [('dwSize', c_long), ('th32ModuleID', c_long),
                    ('th32ProcessID', c_long), ('GlblcntUsage', c_long),
                    ('ProccntUsage', c_long), ('modBaseAddr', c_long),
                    ('modBaseSize', c_long), ('hModule', c_void_p),
                    ('szModule', c_char * 256), ('szExePath', c_char * 260)]

    TH32CS_SNAPPROCESS = 2
    TH32CS_SNAPMODULE = 0x00000008

    ## CreateToolhelp32Snapshot
    CreateToolhelp32Snapshot = windll.kernel32.CreateToolhelp32Snapshot
    CreateToolhelp32Snapshot.reltype = c_long
    CreateToolhelp32Snapshot.argtypes = [c_int, c_int]
    ## Process32First
    Process32First = windll.kernel32.Process32First
    Process32First.argtypes = [c_void_p, POINTER(PROCESSENTRY32)]
    Process32First.rettype = c_int
    ## Process32Next
    Process32Next = windll.kernel32.Process32Next
    Process32Next.argtypes = [c_void_p, POINTER(PROCESSENTRY32)]
    Process32Next.rettype = c_int
    ## CloseHandle
    CloseHandle = windll.kernel32.CloseHandle
    CloseHandle.argtypes = [c_void_p]
    CloseHandle.rettype = c_int
    ## Module32First
    Module32First = windll.kernel32.Module32First
    Module32First.argtypes = [c_void_p, POINTER(MODULEENTRY32)]
    Module32First.rettype = c_int

    hProcessSnap = c_void_p(0)
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)

    pe32 = PROCESSENTRY32()
    pe32.dwSize = sizeof(PROCESSENTRY32)
    ret = Process32First(hProcessSnap, pointer(pe32))
    path = None

    while ret:
        if name + ".exe" == pe32.szExeFile:
            hModuleSnap = c_void_p(0)
            me32 = MODULEENTRY32()
            me32.dwSize = sizeof(MODULEENTRY32)
            hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,
                                                   pe32.th32ProcessID)

            ret = Module32First(hModuleSnap, pointer(me32))
            path = me32.szExePath
            CloseHandle(hModuleSnap)
            if path:
                break
        ret = Process32Next(hProcessSnap, pointer(pe32))
    CloseHandle(hProcessSnap)
    return path
Example #52
0
def adsSyncReadWriteReqEx2(
    port,
    address,
    index_group,
    index_offset,
    read_data_type,
    value,
    write_data_type,
):
    # type: (int, AmsAddr, int, int, Type, Any, Type) -> Any
    """Read and write data synchronous from/to an ADS-device.

    :param int port: local AMS port as returned by adsPortOpenEx()
    :param pyads.structs.AmsAddr address: local or remote AmsAddr
    :param int index_group: PLC storage area, according to the INDEXGROUP
        constants
    :param int index_offset: PLC storage address
    :param Type read_data_type: type of the data given to the PLC to respond to,
        according to PLCTYPE constants
    :param value: value to write to the storage address of the PLC
    :param Type write_data_type: type of the data given to the PLC, according to
        PLCTYPE constants
    :rtype: read_data_type
    :return: value: value read from PLC

    """
    sync_read_write_request = _adsDLL.AdsSyncReadWriteReqEx2

    ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
    index_group_c = ctypes.c_ulong(index_group)
    index_offset_c = ctypes.c_ulong(index_offset)

    if read_data_type == PLCTYPE_STRING:
        read_data = (STRING_BUFFER * PLCTYPE_STRING)()
    else:
        read_data = read_data_type()

    read_data_pointer = ctypes.pointer(read_data)
    read_length = ctypes.c_ulong(ctypes.sizeof(read_data))

    bytes_read = ctypes.c_ulong()
    bytes_read_pointer = ctypes.pointer(bytes_read)

    if write_data_type == PLCTYPE_STRING:
        # Get pointer to string
        write_data_pointer = ctypes.c_char_p(
            value.encode("utf-8")
        )  # type: Union[ctypes.c_char_p, ctypes.pointer]  # noqa: E501
        # Add an extra byte to the data length for the null terminator
        write_length = len(value) + 1
    else:
        write_data = write_data_type(value)
        write_data_pointer = ctypes.pointer(write_data)
        write_length = ctypes.sizeof(write_data)

    err_code = sync_read_write_request(
        port,
        ams_address_pointer,
        index_group_c,
        index_offset_c,
        read_length,
        read_data_pointer,
        write_length,
        write_data_pointer,
        bytes_read_pointer,
    )

    if err_code:
        raise ADSError(err_code)

    # If we're reading a value of predetermined size (anything but a string),
    # validate that the correct number of bytes were read
    if (read_data_type != PLCTYPE_STRING
            and bytes_read.value != read_length.value):
        raise RuntimeError(
            "Insufficient data (expected {0} bytes, {1} were read).".format(
                read_length.value, bytes_read.value))

    if read_data_type == PLCTYPE_STRING:
        return read_data.value.decode("utf-8")

    if type(read_data_type).__name__ == "PyCArrayType":
        return [i for i in read_data]

    if hasattr(read_data, "value"):
        return read_data.value

    return read_data
Example #53
0
 def __init__(self):
     self.mouserect = pygame.Rect(pygame.mouse.get_pos(), (1, 1))
     self.mouseoffset = [0, 0]
     self.posondisplay = [0, 0]
     self.pointstruct = POINT()
     self.pointstructpointer = ctypes.pointer(self.pointstruct)
Example #54
0
 def _get_window_pid(self):
     # Get this window's process ID.
     pid = c_ulong()
     windll.user32.GetWindowThreadProcessId(self._handle, pointer(pid))
     return pid.value
Example #55
0
def loadConfig():

    global sock
    global mode
    global dvfd
    global dmfd
    global fefd

    config = ConfigParser.ConfigParser()
    config.read(sys.argv[1])

    mode = config.get('main', 'mode')

    if mode == 'ip':
        MCAST_GRP = config.get('main', 'source_ip')
        MCAST_PORT = config.getint('main', 'source_port')

        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except AttributeError:
            pass
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
        #    sock.close()
        sock.bind((MCAST_GRP, MCAST_PORT))
        host = socket.gethostbyname(socket.gethostname())
        sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF,
                        socket.inet_aton(host))
        sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
                        socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))

        print 'Listening on ', MCAST_GRP, ':', MCAST_PORT

    if mode == 'dvb':
        print 'Mode DVB'
        adapter = '/dev/dvb/adapter0/'
        fefd = open(adapter + 'frontend0', 'r+')
        feinfo = linuxdvb.dvb_frontend_info()
        fcntl.ioctl(fefd, linuxdvb.FE_GET_INFO, feinfo)
        print feinfo.name

        while True:

            # Tune
            pol = config.get('main', 'pol')
            if (pol == 'V') or (pol == 'v'):
                print 'volt', fcntl.ioctl(fefd, linuxdvb.FE_SET_VOLTAGE,
                                          linuxdvb.SEC_VOLTAGE_13)  #13 - V
            else:
                print 'volt', fcntl.ioctl(fefd, linuxdvb.FE_SET_VOLTAGE,
                                          linuxdvb.SEC_VOLTAGE_18)  #18 - V

            time.sleep(0.250)

            freq = config.getint('main', 'freq')

            if (freq > 11700):
                print 'tone', fcntl.ioctl(fefd, linuxdvb.FE_SET_TONE,
                                          linuxdvb.SEC_TONE_ON)  # ON - 11.7 hi
                loFreq = freq - 10600
            else:
                print 'tone', fcntl.ioctl(
                    fefd, linuxdvb.FE_SET_TONE,
                    linuxdvb.SEC_TONE_OFF)  # OFF - 11.7 hi
                loFreq = freq - 9750

            time.sleep(0.250)

            srate = config.getint('main', 'srate')

            #	dtv_prop = ctypes.POINTER(linuxdvb.dtv_property())
            dtv_prop = linuxdvb.dtv_property()
            dtv_prop.cmd = linuxdvb.DTV_DELIVERY_SYSTEM
            dtv_prop.u.data = linuxdvb.SYS_DVBS2

            dtv_props = linuxdvb.dtv_properties()
            dtv_props.num = 1
            #	dtv_props.props = ctypes.POINTER(dtv_prop)
            #	dtv_props.props = ctypes.cast(dtv_prop, ctypes.POINTER(ctypes.Structure))
            dtv_props.props = ctypes.pointer(dtv_prop)
            print 'props', fcntl.ioctl(fefd, linuxdvb.FE_SET_PROPERTY,
                                       dtv_props)

            params = linuxdvb.dvb_frontend_parameters()
            params.frequency = loFreq * 1000
            params.inversion = linuxdvb.INVERSION_AUTO
            params.u.qpsk.symbol_rate = srate * 1000
            params.u.qpsk.fec_inner = linuxdvb.FEC_AUTO
            print 'front', fcntl.ioctl(fefd, linuxdvb.FE_SET_FRONTEND, params)

            fcntl.ioctl(fefd, linuxdvb.FE_GET_FRONTEND, params)
            print params.u.qpsk.fec_inner

            festatus = linuxdvb.dvb_frontend_event()
            fcntl.ioctl(fefd, linuxdvb.FE_READ_STATUS, festatus)
            if festatus.status & 0x10:
                print "FE_HAS_LOCK"
                break
            else:
                print "No lock!"

        dmfd = open(adapter + 'demux0', 'r+')

        # Pes stream
        pesfilter = linuxdvb.dmx_pes_filter_params()
        pesfilter.pid = 8192
        pesfilter.input = linuxdvb.DMX_IN_FRONTEND
        pesfilter.output = linuxdvb.DMX_OUT_TS_TAP
        pesfilter.pes_type = linuxdvb.DMX_PES_OTHER
        pesfilter.flags = linuxdvb.DMX_IMMEDIATE_START
        fcntl.ioctl(dmfd, linuxdvb.DMX_SET_PES_FILTER, pesfilter)

        dvfd = open(adapter + 'dvr0', 'r')


#	while True:
#	    fcntl.ioctl(fefd, linuxdvb.FE_GET_INFO, feinfo)
#	    print feinfo.frequency
#	    packet = dvr.read(188)
#	    print len(packet)

    newDSTs = {}

    config = ConfigParser.ConfigParser()
    config.read(sys.argv[1])

    for section in config.sections():
        if section != 'main':
            newDSTs[section] = config.getint(section, 'sid')

    global DSTs
    DSTs = newDSTs

    for IP in DSTs:
        datas[IP] = ""
        IP_PID[IP] = []
 def get_device_names(self):
     num_devices = c_int(0)
     r = self.dll.VI_GetDeviceNames(ctypes.pointer(num_devices))
     # ToDo: error validation
     return num_devices.value
Example #57
0
 def __init__(self, srows=64, scols=64, maxmem=100):
     self.srows = srows
     self.scols = scols
     self.maxmem = maxmem
     self.c_seg = ctypes.pointer(libseg.SEGMENT())
Example #58
0
    def __make_interface_pointer(self, itf):
        methods = []  # method implementations
        fields = []  # (name, prototype) for virtual function table
        iids = []  # interface identifiers.
        # iterate over interface inheritance in reverse order to build the
        # virtual function table, and leave out the 'object' base class.
        finder = self._get_method_finder_(itf)
        for interface in itf.__mro__[-2::-1]:
            iids.append(interface._iid_)
            for m in interface._methods_:
                restype, mthname, argtypes, paramflags, idlflags, helptext = m
                proto = WINFUNCTYPE(restype, c_void_p, *argtypes)
                fields.append((mthname, proto))
                mth = finder.get_impl(interface, mthname, paramflags, idlflags)
                methods.append(proto(mth))
        Vtbl = _create_vtbl_type(tuple(fields), itf)
        vtbl = Vtbl(*methods)
        for iid in iids:
            self._com_pointers_[iid] = pointer(pointer(vtbl))
        if hasattr(itf, "_disp_methods_"):
            self._dispimpl_ = {}
            for m in itf._disp_methods_:
                what, mthname, idlflags, restype, argspec = m
                #################
                # What we have:
                #
                # restypes is a ctypes type or None
                # argspec is seq. of (['in'], paramtype, paramname) tuples (or
                # lists?)
                #################
                # What we need:
                #
                # idlflags must contain 'propget', 'propset' and so on:
                # Must be constructed by converting disptype
                #
                # paramflags must be a sequence
                # of (F_IN|F_OUT|F_RETVAL, paramname[, default-value]) tuples
                #
                # comtypes has this function which helps:
                #    def _encode_idl(names):
                #        # convert to F_xxx and sum up "in", "out",
                #        # "retval" values found in _PARAMFLAGS, ignoring
                #        # other stuff.
                #        return sum([_PARAMFLAGS.get(n, 0) for n in names])
                #################

                if what == "DISPMETHOD":
                    if 'propget' in idlflags:
                        invkind = 2  # DISPATCH_PROPERTYGET
                        mthname = "_get_" + mthname
                    elif 'propput' in idlflags:
                        invkind = 4  # DISPATCH_PROPERTYPUT
                        mthname = "_set_" + mthname
                    elif 'propputref' in idlflags:
                        invkind = 8  # DISPATCH_PROPERTYPUTREF
                        mthname = "_setref_" + mthname
                    else:
                        invkind = 1  # DISPATCH_METHOD
                        if restype:
                            argspec = argspec + ((['out'], restype, ""), )
                    self.__make_dispentry(finder, interface, mthname, idlflags,
                                          argspec, invkind)
                elif what == "DISPPROPERTY":
                    # DISPPROPERTY have implicit "out"
                    if restype:
                        argspec += ((['out'], restype, ""), )
                    self.__make_dispentry(
                        finder,
                        interface,
                        "_get_" + mthname,
                        idlflags,
                        argspec,
                        2  # DISPATCH_PROPERTYGET
                    )
                    if not 'readonly' in idlflags:
                        self.__make_dispentry(finder, interface,
                                              "_set_" + mthname, idlflags,
                                              argspec,
                                              4)  # DISPATCH_PROPERTYPUT
Example #59
0
    print 'Version', pa.Pa_GetVersion()
    print 'Version Text', pa.Pa_GetVersionText()
    count = pa.Pa_GetDeviceCount()
    print 'NumDev', count
    for i in range(count):
        pt_info = pa.Pa_GetDeviceInfo(i)
        info = pt_info.contents
        print "Device %2d, host api %s" % (i, pa.Pa_GetHostApiInfo(
            info.hostApi).contents.name)
        print "    Name %s" % info.name
        print "    Max inputs %d,  Max outputs %d" % (info.maxInputChannels,
                                                      info.maxOutputChannels)
        inputParameters.device = i
        outputParameters.device = i
        if info.maxInputChannels >= 2:
            ptIn = ctypes.pointer(inputParameters)
        else:
            ptIn = ctypes.c_void_p()
        if info.maxOutputChannels >= 2:
            ptOut = ctypes.pointer(outputParameters)
        else:
            ptOut = ctypes.c_void_p()
        print "    Speeds for 2-channel paInt32:",
        for speed in (44100, 48000, 96000, 192000):
            if pa.Pa_IsFormatSupported(ptIn, ptOut,
                                       ctypes.c_double(speed)) == 0:
                print "  %d" % speed,
        print
finally:
    print 'Close', pa.Pa_Terminate()
Example #60
0
        ('dwReserved1', DWORD),
        ('dwReserved2', DWORD),
    ]


# Get the number of supported devices (usually 16).
num_devs = joyGetNumDevs()
if num_devs == 0:
    print("Joystick driver not loaded.")

# Number of the joystick to open.
joy_id = 0

# Check if the joystick is plugged in.
info = JOYINFO()
p_info = ctypes.pointer(info)
if joyGetPos(0, p_info) != 0:
    print("Joystick %d not plugged in." % (joy_id + 1))

# Get device capabilities.
caps = JOYCAPS()
if joyGetDevCaps(joy_id, ctypes.pointer(caps), ctypes.sizeof(JOYCAPS)) != 0:
    print("Failed to get device capabilities.")

print "Driver name:", caps.szPname

# Fetch the name from registry.
key = None
if len(caps.szRegKey) > 0:
    try:
        key = winreg.OpenKey(