def set_ad9361_configuration(self, sample_rate=None, tx_carrier_freq=None, rx_carrier_freq=None,
                                 tx_bandwidth=None, rx_bandwidth=None):
        if sample_rate:
            self.sample_rate = int(sample_rate)
            self.tx_bandwidth = min(self.sample_rate//2, 56000000)
            self.rx_bandwidth = min(self.sample_rate//2, 56000000)

        if tx_carrier_freq: self.tx_carrier_freq = int(tx_carrier_freq)
        if rx_carrier_freq: self.rx_carrier_freq = int(rx_carrier_freq)
        if tx_bandwidth:    self.tx_bandwidth    = int(tx_bandwidth)
        if rx_bandwidth:    self.rx_bandwidth    = int(rx_bandwidth)

        # Ensure a sensible sample rate
        if self.interface == "CMOS":
            self.sample_rate = min(self.sample_rate, 61440000)

        # Ensure sensible bandwidths
        self.tx_bandwidth = min(self.tx_bandwidth, self.sample_rate//2, 56000000)
        self.rx_bandwidth = min(self.rx_bandwidth, self.sample_rate//2, 56000000)

        g_lib.ad9361_set_tx_sampling_freq(g_rf_phy, ctypes.c_ulong(self.sample_rate))
        g_lib.ad9361_set_rx_sampling_freq(g_rf_phy, ctypes.c_ulong(self.sample_rate))
        g_lib.ad9361_set_tx_rf_bandwidth(g_rf_phy, ctypes.c_ulong(self.tx_bandwidth))
        g_lib.ad9361_set_rx_rf_bandwidth(g_rf_phy, ctypes.c_ulong(self.rx_bandwidth))

        g_lib.ad9361_set_tx_lo_freq(g_rf_phy, ctypes.c_ulonglong(self.tx_carrier_freq))
        g_lib.ad9361_set_rx_lo_freq(g_rf_phy, ctypes.c_ulonglong(self.rx_carrier_freq))
Пример #2
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
Пример #3
0
def crypto_aead_chacha20poly1305_encrypt(message,
                                         ad,
                                         nonce,
                                         key):

    mlen  = ctypes.c_ulonglong(len(message))

    if ad:
        adlen = ctypes.c_ulonglong(len(ad))
    else:
        adlen = ctypes.c_ulonglong(0)

    c    = ctypes.create_string_buffer(mlen.value+16L)
    clen = ctypes.c_ulonglong(0)

    sodium.crypto_aead_chacha20poly1305_encrypt(c,
                                                ctypes.byref(clen),
                                                message,
                                                mlen,
                                                ad,
                                                adlen,
                                                None,
                                                nonce,
                                                key)
    return c.raw
Пример #4
0
def crypto_aead_chacha20poly1305_decrypt(ciphertext,
                                         ad,
                                         nonce,
                                         key):

    m    = ctypes.create_string_buffer(len(ciphertext)-16L)
    mlen = ctypes.c_ulonglong(0)
    clen = ctypes.c_ulonglong(len(ciphertext))

    if ad:
        adlen = ctypes.c_ulonglong(len(ad))
    else:
        adlen = ctypes.c_ulonglong(0)

    if not sodium.crypto_aead_chacha20poly1305_decrypt(m,
                                                       ctypes.byref(mlen),
                                                       None,
                                                       ciphertext,
                                                       clen,
                                                       ad,
                                                       adlen,
                                                       nonce,
                                                       key) == 0:
        raise ValueError
    else:
        return m.raw
Пример #5
0
    def getDiskSpace(self):

        free_space = {}
        for folder in self.directories():

            size = None
            if os.path.isdir(folder):
                if os.name == 'nt':
                    _, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), \
                                       ctypes.c_ulonglong()
                    if sys.version_info >= (3,) or isinstance(folder, unicode):
                        fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW #@UndefinedVariable
                    else:
                        fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA #@UndefinedVariable
                    ret = fun(folder, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
                    if ret == 0:
                        raise ctypes.WinError()
                    used = total.value - free.value
                    return [total.value, used, free.value]
                else:
                    s = os.statvfs(folder)
                    size = [s.f_blocks * s.f_frsize / (1024 * 1024), (s.f_bavail * s.f_frsize) / (1024 * 1024)]

            free_space[folder] = size

        return free_space
Пример #6
0
 def getmeta(self, meta_name, default=NoDefaultMeta):
     
     if meta_name == 'free_space':
         if platform.system() == 'Windows':
             try:
                 import ctypes
                 free_bytes = ctypes.c_ulonglong(0)
                 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(self.root_path), None, None, ctypes.pointer(free_bytes))
                 return free_bytes.value
             except ImportError:
                 # Fall through to call the base class
                 pass
         else:
             stat = os.statvfs(self.root_path)
             return stat.f_bfree * stat.f_bsize
     elif meta_name == 'total_space':
         if platform.system() == 'Windows':
             try:
                 import ctypes
                 total_bytes = ctypes.c_ulonglong(0)
                 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(self.root_path), None, ctypes.pointer(total_bytes), None)
                 return total_bytes.value
             except ImportError:
                 # Fall through to call the base class
                 pass
         else:
             stat = os.statvfs(self.root_path)
             return stat.f_blocks * stat.f_bsize
     
     return super(OSFS, self).getmeta(meta_name, default)
Пример #7
0
def getFreeSpace(directories):

    single = not isinstance(directories, (tuple, list))
    if single:
        directories = [directories]

    free_space = {}
    for folder in directories:

        size = None
        if os.path.isdir(folder):
            if os.name == "nt":
                _, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), ctypes.c_ulonglong()
                if sys.version_info >= (3,) or isinstance(folder, unicode):
                    fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW  # @UndefinedVariable
                else:
                    fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA  # @UndefinedVariable
                ret = fun(folder, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
                if ret == 0:
                    raise ctypes.WinError()
                return [total.value, free.value]
            else:
                s = os.statvfs(folder)
                size = [s.f_blocks * s.f_frsize / (1024 * 1024), (s.f_bavail * s.f_frsize) / (1024 * 1024)]

        if single:
            return size

        free_space[folder] = size

    return free_space
Пример #8
0
    def disk_usage(self, mount_path):
        """
        Return disk usage statistics about the given path as a (total, used, free)
        namedtuple.  Values are expressed in bytes.
        """
        # Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
        # License: MIT
        _ntuple_diskusage = collections.namedtuple('usage', 'total used free')

        if platform.system() == "Linux":
            st = os.statvfs(mount_path)
            free = st.f_bavail * st.f_frsize
            total = st.f_blocks * st.f_frsize
            used = (st.f_blocks - st.f_bfree) * st.f_frsize

            return _ntuple_diskusage(total, used, free)

        elif platform.system() == "Windows":

            _, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), \
                               ctypes.c_ulonglong()
            if sys.version_info >= (3,) or isinstance(mount_path, unicode):
                fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW
            else:
                fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA
            ret = fun(mount_path, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
            if ret == 0:
                raise ctypes.WinError()
            used = total.value - free.value

            return _ntuple_diskusage(total.value, used, free.value)
        else:
            raise NotImplementedError("Platform not supported.")
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)
Пример #10
0
 def send_mgmt_pending_set(self, pending_timestamp=None, active_timestamp=None, delay_timer=None, channel=None,
                           panid=None, master_key=None, mesh_local=None, network_name=None):
     if pending_timestamp == None:
         pending_timestamp = 0
     if active_timestamp == None:
         active_timestamp = 0
     if delay_timer == None:
         delay_timer = 0
     if panid == None:
         panid = 0
     if channel == None:
         channel = 0
     if master_key == None:
         master_key = ""
     if mesh_local == None:
         mesh_local = ""
     if network_name == None:
         network_name = ""
     if self.Api.otNodeSendPendingSet(
             self.otNode,
             ctypes.c_ulonglong(active_timestamp),
             ctypes.c_ulonglong(pending_timestamp),
             ctypes.c_uint(delay_timer),
             ctypes.c_ushort(panid),
             ctypes.c_ushort(channel),
             master_key.encode('utf-8'),
             mesh_local.encode('utf-8'),
             network_name.encode('utf-8')
         ) != 0:
         raise OSError("otNodeSendPendingSet failed!")
Пример #11
0
def crypto_aead_aes256gcm_decrypt(ctxt, aad, nonce, key):
    """
    Decrypts a ciphertext ctxt given the key, nonce, and aad. If the aad
    or ciphertext were altered then the decryption will fail.
    """
    if not HAS_AEAD_AES256GCM:
        raise ValueError('Underlying Sodium library does not support AES256-GCM AEAD')

    if len(key) != crypto_aead_aes256gcm_KEYBYTES:
        raise ValueError('Invalid key')

    if len(nonce) != crypto_aead_aes256gcm_NPUBBYTES:
        raise ValueError('Invalid nonce')

    length = len(ctxt)-crypto_aead_aes256gcm_ABYTES
    mlen = ctypes.c_ulonglong()
    m = ctypes.create_string_buffer(length)

    ret = nacl.crypto_aead_aes256gcm_decrypt(
        m, ctypes.byref(mlen),
        None,
        ctxt, ctypes.c_ulonglong(len(ctxt)),
        aad, ctypes.c_ulonglong(len(aad)),
        nonce, key)
    if ret:
        raise ValueError('Failed to decrypt message')
    return m.raw
Пример #12
0
def crypto_aead_chacha20poly1305_ietf_decrypt(ctxt, aad, nonce, key):
    """
    Decrypts a ciphertext ctxt given the key, nonce, and aad. If the aad
    or ciphertext were altered then the decryption will fail.
    """
    if not HAS_AEAD_CHACHA20POLY1305_IETF:
        raise ValueError('Underlying Sodium library does not support IETF variant of ChaCha20Poly1305 AEAD')

    if len(key) != crypto_aead_chacha20poly1305_ietf_KEYBYTES:
        raise ValueError('Invalid key')

    if len(nonce) != crypto_aead_chacha20poly1305_ietf_NPUBBYTES:
        raise ValueError('Invalid nonce')

    length = len(ctxt)-crypto_aead_chacha20poly1305_ietf_ABYTES
    mlen = ctypes.c_ulonglong()
    m = ctypes.create_string_buffer(length)

    ret = nacl.crypto_aead_chacha20poly1305_ietf_decrypt(
        m, ctypes.byref(mlen),
        None,
        ctxt, ctypes.c_ulonglong(len(ctxt)),
        aad, ctypes.c_ulonglong(len(aad)),
        nonce, key)
    if ret:
        raise ValueError('Failed to decrypt message')
    return m.raw
Пример #13
0
def crypto_sign_open(sm, pk):
    if sm is None or pk is None:
        raise ValueError("invalid parameters")
    msg = ctypes.create_string_buffer(len(sm))
    msglen = ctypes.c_ulonglong()
    __check(sodium.crypto_sign_open(msg, ctypes.byref(msglen), sm, ctypes.c_ulonglong(len(sm)), pk))
    return msg.raw[:msglen.value]
Пример #14
0
def disk_usage(path):
    if hasattr(os, 'statvfs'):  # POSIX
        st = os.statvfs(path)
        #free = st.f_bavail * st.f_frsize
        total = st.f_blocks * st.f_frsize
        used = (st.f_blocks - st.f_bfree) * st.f_frsize
        #return str(str(used) + '/' + str(total) + 'Mb')
        return str(bytes2human(used) + '/' + bytes2human(total))

    elif os.name == 'nt':       # Windows
        import ctypes
        import sys
        _, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), \
                           ctypes.c_ulonglong()
        if sys.version_info >= (3,) or isinstance(path, unicode):
            fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW
        else:
            fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA
        ret = fun(path,
                  ctypes.byref(_),
                  ctypes.byref(total),
                  ctypes.byref(free)
                  )
        if ret == 0:
            raise ctypes.WinError()
        used = total.value - free.value
        return str(bytes2human(used) + '/' + bytes2human(total.value))
        #return str( str(round(used/1024/1024, 2) ) + '/' +
        #            str(round(total.value/1024/1024, 2)) + 'Mb')
    else:
        raise NotImplementedError("platform not supported")
Пример #15
0
def get_lobbies(slots, location):
    AddRequestLobbyListResultCountFilter(SteamMatchmaking, 500)
    AddRequestLobbyListFilterSlotsAvailable(SteamMatchmaking, slots)
    AddRequestLobbyListDistanceFilter(SteamMatchmaking, location)
    apicall = ctypes.c_ulonglong(RequestLobbyList(SteamMatchmaking))
    failed = ctypes.c_bool(False)
    while not IsAPICallCompleted(SteamUtils, apicall, ctypes.byref(failed)):
        pass
    ret = ctypes.c_uint32()
    GetAPICallResult(SteamUtils, apicall, ctypes.byref(ret),
                     ctypes.sizeof(ctypes.c_uint32), 510, ctypes.byref(failed))
    lobbies = []
    for i in range(ret.value):
        steam_id = ctypes.c_ulonglong(GetLobbyByIndex(SteamMatchmaking, i))
        members = GetNumLobbyMembers(SteamMatchmaking, steam_id)
        meta_count = GetLobbyDataCount(SteamMatchmaking, steam_id)
        if not meta_count:
            continue
        lobby = Lobby(steam_id.value, members)
        lobbies.append(lobby)
        for ii in range(meta_count):
            key = ctypes.create_string_buffer(BUFFER_SIZE)
            value = ctypes.create_string_buffer(BUFFER_SIZE)
            GetLobbyDataByIndex(SteamMatchmaking, steam_id, ii,
                                key, BUFFER_SIZE,
                                value, BUFFER_SIZE)
            lobby.data[key.value.decode('utf-8')] = value.value.decode('utf-8')
    return lobbies
Пример #16
0
def crypto_sign(m, sk):
    if None in (m, sk): raise ValueError
    smsg = ctypes.create_string_buffer(len(m)+crypto_sign_BYTES)
    smsglen = ctypes.pointer(ctypes.c_ulonglong())
    if not sodium.crypto_sign(smsg, smsglen, m, ctypes.c_ulonglong(len(m)), sk) == 0:
        raise ValueError
    return smsg.raw
Пример #17
0
def getDiskUsage(path):
    _ntuple_diskusage = collections.namedtuple('usage', 'total used free')

    if hasattr(os, 'statvfs'):  # POSIX
        st = os.statvfs(path)
        free = st.f_bavail * st.f_frsize
        total = st.f_blocks * st.f_frsize
        used = (st.f_blocks - st.f_bfree) * st.f_frsize
        return _ntuple_diskusage(total, used, free)

    elif os.name == 'nt':       # Windows
        import ctypes
        import sys

        _, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), ctypes.c_ulonglong()
        if sys.version_info >= (3,) or isinstance(path, str):
            fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW
        else:
            fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA
        ret = fun(path, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
        if ret == 0:
            raise ctypes.WinError()
        used = total.value - free.value
        return _ntuple_diskusage(total.value, used, free.value)
    else:
        raise NotImplementedError("platform not supported")
Пример #18
0
def get_free_space(folder, units="MB"):
    """
        Return folder/drive free space (Free Space, total space, units)

        :type folder: str
        :return: A Dict with items: units, bytes_per_unit, folder, free, total
        :rtype: dict
    """

    u_constants = get_byte_unit_def(units)
    disk_info = {
        'units': units,
        'bytes_per_unit': u_constants,
        'folder': folder
    }

    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        total_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, ctypes.pointer(total_bytes),
                                                   ctypes.pointer(free_bytes))

        disk_info['free'] = int(free_bytes.value / u_constants)
        disk_info['total'] = int(total_bytes.value / u_constants)

        # return int(free_bytes.value / u_constants), int(total_bytes.value / u_constants), units
        return disk_info
    else:
        disk_info['free'] = int(os.statvfs(folder).f_bfree * os.statvfs(folder).f_bsize / u_constants)
        disk_info['total'] = int(os.statvfs(folder).f_blocks * os.statvfs(folder).f_bsize / u_constants)

        # return int(os.statvfs(folder).f_bfree * os.statvfs(folder).f_bsize / u_constants), units
        return disk_info
Пример #19
0
    def get_free_disk_space(self, path):
        """
        Determine the percentage of free disk space.

        Keyword arguments:
        path -- the path to the drive to check (this can be any path of any length on the desired drive).
        If the path doesn't exist, this function returns 100, in order to prevent files from being deleted accidentally.
        """
        percentage = 100
        self.debug("path is: " + path)
        if os.path.exists(path) or r"://" in path: #os.path.exists() doesn't work for non-UNC network paths
            if platform.system() == "Windows":
                self.debug("We are checking disk space from a Windows file system")
                self.debug("Stripping " + path + " of all redundant stuff.")

                if r"://" in path:
                    self.debug("We are dealing with network paths:\n" + path)
                    # TODO: Verify this regex captures all possible usernames and passwords.
                    pattern = re.compile("(?P<protocol>smb|nfs)://(?P<user>\w+):(?P<pass>[\w\-]+)@(?P<host>\w+)", re.I)
                    match = pattern.match(path)
                    share = match.groupdict()
                    self.debug("Regex result:\nprotocol: %s\nuser: %s\npass: %s\nhost: %s" % (share['protocol'], share['user'], share['pass'], share['host']))
                    path = path[match.end():]
                    self.debug("Creating UNC paths, so Windows understands the shares, result:\n" + path)
                    path = os.path.normcase(r"\\" + share["host"] + path)
                    self.debug("os.path.normcase result:\n" + path)
                else:
                    self.debug("We are dealing with local paths:\n" + path)

                if not isinstance(path, unicode):
                    path = path.decode('mbcs')

                totalNumberOfBytes = c_ulonglong(0)
                totalNumberOfFreeBytes = c_ulonglong(0)

                # GetDiskFreeSpaceEx explained: http://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx
                windll.kernel32.GetDiskFreeSpaceExW(c_wchar_p(path), pointer(totalNumberOfBytes), pointer(totalNumberOfFreeBytes), None)

                free = float(totalNumberOfBytes.value)
                capacity = float(totalNumberOfFreeBytes.value)

                try:
                    percentage = float(free / capacity * float(100))
                    self.debug("Hard disk checks returned the following results:\n%s: %f\n%s: %f\n%s: %f" % ("free", free, "capacity", capacity, "percentage", percentage))
                except ZeroDivisionError, e:
                    self.notify(__settings__.getLocalizedString(34011), 15000)
            else:
                self.debug("We are checking disk space from a non-Windows file system")
                self.debug("Stripping " + path + " of all redundant stuff.")
                drive = os.path.normpath(path)
                self.debug("The path now is " + drive)

                try:
                    diskstats = os.statvfs(path)
                    percentage = float(diskstats.f_bfree / diskstats.f_blocks * float(100))
                    self.debug("Hard disk checks returned the following results:\n%s: %f\n%s: %f\n%s: %f" % ("free blocks", diskstats.f_bfree, "total blocks", diskstats.f_blocks, "percentage", percentage))
                except OSError, e:
                    self.notify(__settings__.getLocalizedString(34012) % self.diskSpacePath)
                except ZeroDivisionError, zde:
                    self.notify(__settings__.getLocalizedString(34011), 15000)
Пример #20
0
 def get_process_creation_time(self, process):
     '''
     Return the creation time of a given process.
     
     :param process: the process to check for creation time
     :type process: int
     
     :return: the process creation time from time stamp
     :rtype: int
     '''
     
     creationtime = ctypes.c_ulonglong()
     exittime = ctypes.c_ulonglong()
     kerneltime = ctypes.c_ulonglong()
     usertime = ctypes.c_ulonglong()
     rc = ctypes.windll.kernel32.GetProcessTimes(process,
                                                 ctypes.byref(creationtime),
                                                 ctypes.byref(exittime),
                                                 ctypes.byref(kerneltime),
                                                 ctypes.byref(usertime))
     
     
     creationtime.value -= ctypes.c_longlong(116444736000000000L).value
     creationtime.value /= 10000000
     
     return creationtime.value    
Пример #21
0
 def setCountLength(self, N, BufferLength=None, SampleLength=None):
     """
     Set the number of counter samples / length of pulse train. If N is finite, a finite pulse train
     of length N is generated and N count samples are acquired. If N is infinity, an infinite pulse
     train is generated. BufferLength and SampleLength specify the length of the buffer and the length
     of a sample that is read in one read operation. In this case, always the most recent samples are read.
     """
     if N < numpy.inf:
         CHK(  dll.DAQmxCfgImplicitTiming( self.COTask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(N))  )
         CHK(  dll.DAQmxCfgImplicitTiming( self.CITask, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(N))  )
         # read samples from beginning of acquisition, do not overwrite
         CHK( dll.DAQmxSetReadRelativeTo(self.CITask, DAQmx_Val_CurrReadPos) )
         CHK( dll.DAQmxSetReadOffset(self.CITask, 0) )
         CHK( dll.DAQmxSetReadOverWrite(self.CITask, DAQmx_Val_DoNotOverwriteUnreadSamps) )
         self._CountSamples = N
         self._TaskTimeout = 4 * N / self._f
     else:
         CHK(  dll.DAQmxCfgImplicitTiming( self.COTask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(BufferLength))  )
         CHK(  dll.DAQmxCfgImplicitTiming( self.CITask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(BufferLength))  )
         # read most recent samples, overwrite buffer
         CHK( dll.DAQmxSetReadRelativeTo(self.CITask, DAQmx_Val_MostRecentSamp) )
         CHK( dll.DAQmxSetReadOffset(self.CITask, -SampleLength) )
         CHK( dll.DAQmxSetReadOverWrite(self.CITask, DAQmx_Val_OverwriteUnreadSamps) )
         self._CountSamples = SampleLength
     self._CountLength = N
     self._CIData = numpy.empty((self._CountSamples,), dtype=numpy.uint32)
Пример #22
0
 def configure(self, n_samples, seconds_per_point):
     """
     Configures the sampling length and rate.
     
         n==0:    single point
         0<n<Inf: single waveform
     """
     if n_samples == 0:
         CHK( dll.DAQmxSetSampTimingType(self.ao_task, DAQmx_Val_OnDemand) )
     elif n_samples < numpy.inf:
         f = 1./seconds_per_point
         CHK( dll.DAQmxSetSampTimingType(self.ao_task, DAQmx_Val_SampClk) )
         CHK( dll.DAQmxCfgSampClkTiming(self.ao_task,
                                        self.co_dev+'InternalOutput',
                                        ctypes.c_double(f),
                                        DAQmx_Val_Falling,
                                        DAQmx_Val_FiniteSamps,
                                        ctypes.c_ulonglong(n_samples)) )
         CHK( dll.DAQmxSetCOPulseFreq(self.co_task,
                                      self.co_dev,
                                      ctypes.c_double(f)
                                      ))
         CHK( dll.DAQmxCfgImplicitTiming(self.co_task,
                                         DAQmx_Val_ContSamps,
                                         ctypes.c_ulonglong(n_samples+1)
                                         ))
         CHK( dll.DAQmxCfgImplicitTiming(self.ci_task,
                                         DAQmx_Val_FiniteSamps,
                                         ctypes.c_ulonglong(n_samples+1)
                                         ))
         self.ci_data = numpy.empty((n_samples+1,), dtype=numpy.uint32)
Пример #23
0
def crypto_sign(m, sk):
    if m is None or sk is None:
        raise ValueError("invalid parameters")
    smsg = ctypes.create_string_buffer(len(m) + crypto_sign_BYTES)
    smsglen = ctypes.c_ulonglong()
    __check(sodium.crypto_sign(smsg, ctypes.byref(smsglen), m, ctypes.c_ulonglong(len(m)), sk))
    return smsg.raw
Пример #24
0
 def get_rectangle(self):
     """Get the bounding rectangle that tesseract is looking at inside
     of the image.
     """
     left, top = c_ulonglong(), c_ulonglong()
     width, height = c_ulonglong(), c_ulonglong()
     tr.Tesserwrap_GetRectangle(self.handle, byref(left), byref(top), byref(width), byref(height))
     return ((left.value, top.value), (width.value, height.value))
Пример #25
0
def crypto_sign_open(sm, pk):
    if None in (sm, pk): raise ValueError
    msg = ctypes.create_string_buffer(len(sm))
    msglen = ctypes.c_ulonglong()
    msglenp = ctypes.pointer(msglen)
    if not sodium.crypto_sign_open(msg, msglenp, sm, ctypes.c_ulonglong(len(sm)), pk) == 0:
        raise ValueError
    return msg.raw[:msglen.value]
Пример #26
0
def crypto_aead_chacha20poly1305_ietf_decrypt(ciphertext, ad, nonce, key):

    m = ctypes.create_string_buffer(len(ciphertext) - 16)
    mlen = ctypes.c_ulonglong(0)
    clen = ctypes.c_ulonglong(len(ciphertext))
    adlen = ctypes.c_ulonglong(len(ad))
    __check(sodium.crypto_aead_chacha20poly1305_ietf_decrypt(m, ctypes.byref(mlen), None, ciphertext, clen, ad, adlen, nonce, key))
    return m.raw
Пример #27
0
def windows_disk_look(dir):
    """ Function just for windows (called below if needed). """
    total_bytes = ctypes.c_ulonglong(0)
    free_bytes = ctypes.c_ulonglong(0)
    ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dir), None, ctypes.pointer(total_bytes), ctypes.pointer(free_bytes))
    a = total_bytes.value / 1024 / 1024  # MEGABYTES FORMAT
    b = free_bytes.value / 1024 / 1024
    retlist = [a, b]
    return retlist
Пример #28
0
def crypto_aead_chacha20poly1305_decrypt(ciphertext, ad, nonce, key):

    if ad == None: raise ValueError("ad cannot be None")
    m = ctypes.create_string_buffer(len(ciphertext) - 16)
    mlen = ctypes.c_ulonglong(0)
    clen = ctypes.c_ulonglong(len(ciphertext))
    adlen = ctypes.c_ulonglong(len(ad))
    __check(sodium.crypto_aead_chacha20poly1305_decrypt(m, ctypes.byref(mlen), None, ciphertext, clen, ad, adlen, nonce, key))
    return m.raw
Пример #29
0
def crypto_aead_chacha20poly1305_ietf_encrypt(message, ad, nonce, key):

    mlen = ctypes.c_ulonglong(len(message))
    adlen = ctypes.c_ulonglong(len(ad))
    c = ctypes.create_string_buffer(mlen.value + 16)
    clen = ctypes.c_ulonglong(0)

    __check(sodium.crypto_aead_chacha20poly1305_ietf_encrypt(c, ctypes.byref(clen), message, mlen, ad, adlen, None, nonce, key))
    return c.raw
Пример #30
0
Файл: helpers.py Проект: vadv/cm
	def get_drive_info(cls, drive):
		_diskusage = namedtuple('disk_usage', 'total used free')
		used, total, free = c_ulonglong(), c_ulonglong(), c_ulonglong()
		drive = drive + ':\\'
		ret = kernel32.GetDiskFreeSpaceExA(str(drive), byref(used), byref(total), byref(free))
		if ret == 0:
			raise
		else:
			return _diskusage(total.value, used, free.value)
Пример #31
0
def QwordToDouble(value):
    p = ctypes.pointer(ctypes.c_ulonglong(value))
    p = ctypes.cast(p, ctypes.POINTER(ctypes.c_double))
    return p.contents.value
Пример #32
0
 def resolve(self, phys_addr):
     self._assert_dlls()
     cpa = ctypes.c_ulonglong(phys_addr)
     return _lib.ramses_resolve(ctypes.byref(self), cpa)
    i = i + 1
    if verbose == False:
        progress(files_to_process, 40, i)  # show progress bar
    #file_size=file_size/1024 # convert KB first
    # round up to ceiling 8kb (Isilon uses an 8KB filesystem block size, so we need to round up)

    if (block_size == 0):
        testfs = file_size
        try:
            block_size = os.statvfs(
                dirname
            ).f_frsize  #try to find the native FS block size using Unix stats command (will fail in Windows based OS)
        except AttributeError:  # if above command fails, let's try finding the native FS block size using Windows native DLL instead
            import ctypes

            sectorsPerCluster = ctypes.c_ulonglong(0)
            bytesPerSector = ctypes.c_ulonglong(0)
            rootPathName = ctypes.c_wchar_p(dirname)

            ctypes.windll.kernel32.GetDiskFreeSpaceW(
                rootPathName,
                ctypes.pointer(sectorsPerCluster),
                ctypes.pointer(bytesPerSector),
                None,
                None,
            )
            spc = sectorsPerCluster.value
            bps = bytesPerSector.value
            block_size = spc * bps

    #Round all the filesize calculations (for the original data size) to the blocksize of the native filesystem (of the system this script is running on)
Пример #34
0
 def lib_call(key, msg, hex_out=True):
     if args.debug:
         _print_data(msg)
     ret = '\x00' * 16
     func(key, msg, ctypes.c_ulonglong(len(msg)), ret)
     return ret.encode('hex') if hex_out else ret
Пример #35
0
	def __init__(self, src, begin = 0, end = -1):
		self.m_src = src
		self.m_cptr = native.n_dvrange_create(src.m_cptr, ctypes.c_ulonglong(begin).value, ctypes.c_ulonglong(end).value)
Пример #36
0
 def __init__(self, src, begin = 0, end = -1):
     self.m_src = src
     self.m_cptr = native.n_dvbuffer_range_from_dvbuffer(src.m_cptr, ctypes.c_ulonglong(begin).value, ctypes.c_ulonglong(end).value)
Пример #37
0
def eventfd_write(fd, value: int) -> None:
    _eventfd_value_check(value)

    bytes_written = os.write(fd, c_ulonglong(value))
    if bytes_written != 8:
        raise Exception("bytes_written (%d) != 8", bytes_written)
Пример #38
0
 def __new__(cls, value=0):
     return cls.from_buffer_copy(ctypes.c_ulonglong(value))
Пример #39
0
a['OptionParserType'] = _oparser = optparse.OptionParser()  # pickle ok
a['OptionGroupType'] = optparse.OptionGroup(_oparser, "foo")  # pickle ok
a['OptionType'] = optparse.Option('--foo')  # pickle ok
if HAS_CTYPES:
    a['CCharType'] = _cchar = ctypes.c_char()
    a['CWCharType'] = ctypes.c_wchar()  # fail == 2.6
    a['CByteType'] = ctypes.c_byte()
    a['CUByteType'] = ctypes.c_ubyte()
    a['CShortType'] = ctypes.c_short()
    a['CUShortType'] = ctypes.c_ushort()
    a['CIntType'] = ctypes.c_int()
    a['CUIntType'] = ctypes.c_uint()
    a['CLongType'] = ctypes.c_long()
    a['CULongType'] = ctypes.c_ulong()
    a['CLongLongType'] = ctypes.c_longlong()
    a['CULongLongType'] = ctypes.c_ulonglong()
    a['CFloatType'] = ctypes.c_float()
    a['CDoubleType'] = ctypes.c_double()
    a['CSizeTType'] = ctypes.c_size_t()
    a['CLibraryLoaderType'] = ctypes.cdll
    a['StructureType'] = _Struct
    a['BigEndianStructureType'] = ctypes.BigEndianStructure()
#NOTE: also LittleEndianStructureType and UnionType... abstract classes
#NOTE: remember for ctypesobj.contents creates a new python object
#NOTE: ctypes.c_int._objects is memberdescriptor for object's __dict__
#NOTE: base class of all ctypes data types is non-public _CData

try:  # python 2.6
    import fractions
    import number
    import io
Пример #40
0
 def resolve_name(self, name):
     addr = ct.c_ulonglong()
     if lib.bcc_symcache_resolve_name(self.cache, name,
                                      ct.pointer(addr)) < 0:
         return -1
     return addr.value
Пример #41
0
        window.title("agora for test")
        window.geometry('480x960')

        NUMBER_OF_FRAMES = 8
        relative_height = 1 / float(NUMBER_OF_FRAMES)

        for number in range(NUMBER_OF_FRAMES):
            display_frame = tkinter.Frame(window, bg='')
            relative_y = number * relative_height
            display_frame.place(relx=0,
                                rely=relative_y,
                                anchor=tkinter.NW,
                                relwidth=1,
                                relheight=relative_height)
            frame_id = display_frame.winfo_id()
            agora.addView(ctypes.c_ulonglong(frame_id))

        agora.createEngine(ctypes.c_char_p(bytes(app_id, 'utf-8')))

        enableAudio = json.dumps({"enable": "true"})
        if disableAudio == True:
            enableAudio = json.dumps({"enable": "false"})
        agora.enableAudio(ctypes.c_char_p(bytes(enableAudio, 'utf-8')))

        enableVideo = json.dumps({"enable": "true"})
        if disableVideo == True:
            enableVideo = json.dumps({"enable": "false"})
        agora.enableVideo(ctypes.c_char_p(bytes(enableVideo, 'utf-8')))

        if baselineVideo == True:
            #100:high, 66:baseline
Пример #42
0
def windowsSpecificGetFreeSpace(drive):
    freeSpace = ctypes.c_ulonglong(0)
    ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(drive), None,
                                               None, ctypes.pointer(freeSpace))
    return freeSpace.value
Пример #43
0
def get_disk_stats(whichdir, reserved_space=0):
    """Return disk statistics for the storage disk, in the form of a dict
    with the following fields.
      total:            total bytes on disk
      free_for_root:    bytes actually free on disk
      free_for_nonroot: bytes free for "a non-privileged user" [Unix] or
                          the current user [Windows]; might take into
                          account quotas depending on platform
      used:             bytes used on disk
      avail:            bytes available excluding reserved space
    An AttributeError can occur if the OS has no API to get disk information.
    An EnvironmentError can occur if the OS call fails.

    whichdir is a directory on the filesystem in question -- the
    answer is about the filesystem, not about the directory, so the
    directory is used only to specify which filesystem.

    reserved_space is how many bytes to subtract from the answer, so
    you can pass how many bytes you would like to leave unused on this
    filesystem as reserved_space.
    """

    if have_GetDiskFreeSpaceExW:
        # If this is a Windows system and GetDiskFreeSpaceExW is available, use it.
        # (This might put up an error dialog unless
        # SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX) has been called,
        # which we do in allmydata.windows.fixups.initialize().)

        n_free_for_nonroot = c_ulonglong(0)
        n_total            = c_ulonglong(0)
        n_free_for_root    = c_ulonglong(0)
        retval = GetDiskFreeSpaceExW(whichdir, byref(n_free_for_nonroot),
                                               byref(n_total),
                                               byref(n_free_for_root))
        if retval == 0:
            raise OSError("Windows error %d attempting to get disk statistics for %r"
                          % (GetLastError(), whichdir))
        free_for_nonroot = n_free_for_nonroot.value
        total            = n_total.value
        free_for_root    = n_free_for_root.value
    else:
        # For Unix-like systems.
        # <http://docs.python.org/library/os.html#os.statvfs>
        # <http://opengroup.org/onlinepubs/7990989799/xsh/fstatvfs.html>
        # <http://opengroup.org/onlinepubs/7990989799/xsh/sysstatvfs.h.html>
        s = os.statvfs(whichdir)

        # on my mac laptop:
        #  statvfs(2) is a wrapper around statfs(2).
        #    statvfs.f_frsize = statfs.f_bsize :
        #     "minimum unit of allocation" (statvfs)
        #     "fundamental file system block size" (statfs)
        #    statvfs.f_bsize = statfs.f_iosize = stat.st_blocks : preferred IO size
        # on an encrypted home directory ("FileVault"), it gets f_blocks
        # wrong, and s.f_blocks*s.f_frsize is twice the size of my disk,
        # but s.f_bavail*s.f_frsize is correct

        total = s.f_frsize * s.f_blocks
        free_for_root = s.f_frsize * s.f_bfree
        free_for_nonroot = s.f_frsize * s.f_bavail

    # valid for all platforms:
    used = total - free_for_root
    avail = max(free_for_nonroot - reserved_space, 0)

    return { 'total': total,
             'free_for_root': free_for_root,
             'free_for_nonroot': free_for_nonroot,
             'used': used,
             'avail': avail,
           }
Пример #44
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()
Пример #45
0
 def get_free_space(self, path):
     free_bytes = ctypes.c_ulonglong(0)
     ctypes.windll.kernel32.GetDiskFreeSpaceExW(
         ctypes.c_wchar_p(path.decode('ascii')), None, None,
         ctypes.pointer(free_bytes))
     return free_bytes.value
Пример #46
0
 def createBuffers(self):
     self.filename = ctypes.create_unicode_buffer(260)
     self.date_modified_filetime = ctypes.c_ulonglong(1)
     self.file_size = ctypes.c_ulonglong(1)
Пример #47
0
    def __init__(self,
                 arch: Optional['architecture.Architecture'] = None,
                 name: Optional[str] = None,
                 handle=None,
                 confidence: int = core.max_confidence):
        if handle is None:
            if arch is None or name is None:
                raise ValueError(
                    "Must specify either handle or architecture and name")
            self._arch = arch
            self._pending_reg_lists = {}
            self._cb = core.BNCustomCallingConvention()
            self._cb.context = 0
            self._cb.getCallerSavedRegisters = self._cb.getCallerSavedRegisters.__class__(
                self._get_caller_saved_regs)
            self._cb.getCalleeSavedRegisters = self._cb.getCalleeSavedRegisters.__class__(
                self._get_callee_saved_regs)
            self._cb.getIntegerArgumentRegisters = self._cb.getIntegerArgumentRegisters.__class__(
                self._get_int_arg_regs)
            self._cb.getFloatArgumentRegisters = self._cb.getFloatArgumentRegisters.__class__(
                self._get_float_arg_regs)
            self._cb.freeRegisterList = self._cb.freeRegisterList.__class__(
                self._free_register_list)
            self._cb.areArgumentRegistersSharedIndex = self._cb.areArgumentRegistersSharedIndex.__class__(
                self._arg_regs_share_index)
            self._cb.areArgumentRegistersUsedForVarArgs = self._cb.areArgumentRegistersUsedForVarArgs.__class__(
                self._arg_regs_used_for_varargs)
            self._cb.isStackReservedForArgumentRegisters = self._cb.isStackReservedForArgumentRegisters.__class__(
                self._stack_reserved_for_arg_regs)
            self._cb.isStackAdjustedOnReturn = self._cb.isStackAdjustedOnReturn.__class__(
                self._stack_adjusted_on_return)
            self._cb.isEligibleForHeuristics = self._cb.isEligibleForHeuristics.__class__(
                self._eligible_for_heuristics)
            self._cb.getIntegerReturnValueRegister = self._cb.getIntegerReturnValueRegister.__class__(
                self._get_int_return_reg)
            self._cb.getHighIntegerReturnValueRegister = self._cb.getHighIntegerReturnValueRegister.__class__(
                self._get_high_int_return_reg)
            self._cb.getFloatReturnValueRegister = self._cb.getFloatReturnValueRegister.__class__(
                self._get_float_return_reg)
            self._cb.getGlobalPointerRegister = self._cb.getGlobalPointerRegister.__class__(
                self._get_global_pointer_reg)
            self._cb.getImplicitlyDefinedRegisters = self._cb.getImplicitlyDefinedRegisters.__class__(
                self._get_implicitly_defined_regs)
            self._cb.getIncomingRegisterValue = self._cb.getIncomingRegisterValue.__class__(
                self._get_incoming_reg_value)
            self._cb.getIncomingFlagValue = self._cb.getIncomingFlagValue.__class__(
                self._get_incoming_flag_value)
            self._cb.getIncomingVariableForParameterVariable = self._cb.getIncomingVariableForParameterVariable.__class__(
                self._get_incoming_var_for_parameter_var)
            self._cb.getParameterVariableForIncomingVariable = self._cb.getParameterVariableForIncomingVariable.__class__(
                self._get_parameter_var_for_incoming_var)
            _handle = core.BNCreateCallingConvention(arch.handle, name,
                                                     self._cb)
            self.__class__._registered_calling_conventions.append(self)
        else:
            _handle = handle
            self.arch = architecture.CoreArchitecture._from_cache(
                core.BNGetCallingConventionArchitecture(_handle))
            self.__dict__["name"] = core.BNGetCallingConventionName(_handle)
            self.__dict__[
                "arg_regs_share_index"] = core.BNAreArgumentRegistersSharedIndex(
                    _handle)
            self.__dict__[
                "arg_regs_for_varargs"] = core.BNAreArgumentRegistersUsedForVarArgs(
                    _handle)
            self.__dict__[
                "stack_reserved_for_arg_regs"] = core.BNIsStackReservedForArgumentRegisters(
                    _handle)
            self.__dict__[
                "stack_adjusted_on_return"] = core.BNIsStackAdjustedOnReturn(
                    _handle)
            self.__dict__[
                "eligible_for_heuristics"] = core.BNIsEligibleForHeuristics(
                    _handle)

            count = ctypes.c_ulonglong()
            regs = core.BNGetCallerSavedRegisters(_handle, count)
            assert regs is not None, "core.BNGetCallerSavedRegisters returned None"
            result = []
            arch = self.arch
            for i in range(0, count.value):
                result.append(arch.get_reg_name(regs[i]))
            core.BNFreeRegisterList(regs)
            self.__dict__["caller_saved_regs"] = result

            count = ctypes.c_ulonglong()
            regs = core.BNGetCalleeSavedRegisters(_handle, count)
            assert regs is not None, "core.BNGetCalleeSavedRegisters returned None"
            result = []
            arch = self.arch
            for i in range(0, count.value):
                result.append(arch.get_reg_name(regs[i]))
            core.BNFreeRegisterList(regs)
            self.__dict__["callee_saved_regs"] = result

            count = ctypes.c_ulonglong()
            regs = core.BNGetIntegerArgumentRegisters(_handle, count)
            assert regs is not None, "core.BNGetIntegerArgumentRegisters returned None"
            result = []
            arch = self.arch
            for i in range(0, count.value):
                result.append(arch.get_reg_name(regs[i]))
            core.BNFreeRegisterList(regs)
            self.__dict__["int_arg_regs"] = result

            count = ctypes.c_ulonglong()
            regs = core.BNGetFloatArgumentRegisters(_handle, count)
            assert regs is not None, "core.BNGetFloatArgumentRegisters returned None"
            result = []
            arch = self.arch
            for i in range(0, count.value):
                result.append(arch.get_reg_name(regs[i]))
            core.BNFreeRegisterList(regs)
            self.__dict__["float_arg_regs"] = result

            reg = core.BNGetIntegerReturnValueRegister(_handle)
            if reg == 0xffffffff:
                self.__dict__["int_return_reg"] = None
            else:
                self.__dict__["int_return_reg"] = self.arch.get_reg_name(reg)

            reg = core.BNGetHighIntegerReturnValueRegister(_handle)
            if reg == 0xffffffff:
                self.__dict__["high_int_return_reg"] = None
            else:
                self.__dict__["high_int_return_reg"] = self.arch.get_reg_name(
                    reg)

            reg = core.BNGetFloatReturnValueRegister(_handle)
            if reg == 0xffffffff:
                self.__dict__["float_return_reg"] = None
            else:
                self.__dict__["float_return_reg"] = self.arch.get_reg_name(reg)

            reg = core.BNGetGlobalPointerRegister(_handle)
            if reg == 0xffffffff:
                self.__dict__["global_pointer_reg"] = None
            else:
                self.__dict__["global_pointer_reg"] = self.arch.get_reg_name(
                    reg)

            count = ctypes.c_ulonglong()
            regs = core.BNGetImplicitlyDefinedRegisters(_handle, count)
            assert regs is not None, "core.BNGetImplicitlyDefinedRegisters returned None"
            result = []
            arch = self.arch
            for i in range(0, count.value):
                result.append(arch.get_reg_name(regs[i]))
            core.BNFreeRegisterList(regs)
            self.__dict__["implicitly_defined_regs"] = result
        assert _handle is not None
        self.handle = _handle
        self.confidence = confidence
Пример #48
0
 def unpack_data(self, data):
     data = data & self._data_mask
     if self._datatype == DataType.Sgl:
         return ctypes.c_float.from_buffer(ctypes.c_uint(data)).value
     if self._datatype == DataType.Dbl:
         return ctypes.c_double.from_buffer(ctypes.c_ulonglong(data)).value
Пример #49
0
def get_environment():
    """
    Devuelve las variables de entorno del OS, de Kodi y de Alfa más habituales,
    necesarias para el diagnóstico de fallos 
    """

    try:
        import base64
        import ast

        environment = config.get_platform(full_version=True)
        environment['num_version'] = str(environment['num_version'])
        environment['python_version'] = str(platform.python_version())

        environment['os_release'] = str(platform.release())
        if xbmc.getCondVisibility("system.platform.Windows"):
            try:
                if platform._syscmd_ver()[2]:
                    environment['os_release'] = str(platform._syscmd_ver()[2])
            except:
                pass
        environment['prod_model'] = ''
        if xbmc.getCondVisibility("system.platform.Android"):
            environment['os_name'] = 'Android'
            try:
                for label_a in subprocess.check_output('getprop').split('\n'):
                    if 'build.version.release' in label_a:
                        environment['os_release'] = str(
                            scrapertools.find_single_match(
                                label_a, ':\s*\[(.*?)\]$'))
                    if 'product.model' in label_a:
                        environment['prod_model'] = str(
                            scrapertools.find_single_match(
                                label_a, ':\s*\[(.*?)\]$'))
            except:
                try:
                    for label_a in filetools.read(os.environ['ANDROID_ROOT'] +
                                                  '/build.prop').split():
                        if 'build.version.release' in label_a:
                            environment['os_release'] = str(
                                scrapertools.find_single_match(
                                    label_a, '=(.*?)$'))
                        if 'product.model' in label_a:
                            environment['prod_model'] = str(
                                scrapertools.find_single_match(
                                    label_a, '=(.*?)$'))
                except:
                    pass

        elif xbmc.getCondVisibility("system.platform.Linux.RaspberryPi"):
            environment['os_name'] = 'RaspberryPi'
        else:
            environment['os_name'] = str(platform.system())

        environment['machine'] = str(platform.machine())
        environment['architecture'] = str(sys.maxsize > 2**32 and "64-bit"
                                          or "32-bit")
        environment['language'] = str(xbmc.getInfoLabel('System.Language'))

        environment['cpu_usage'] = str(xbmc.getInfoLabel('System.CpuUsage'))

        environment['mem_total'] = str(
            xbmc.getInfoLabel('System.Memory(total)')).replace('MB',
                                                               '').replace(
                                                                   'KB', '')
        environment['mem_free'] = str(
            xbmc.getInfoLabel('System.Memory(free)')).replace('MB',
                                                              '').replace(
                                                                  'KB', '')
        if not environment['mem_total'] or not environment['mem_free']:
            try:
                if environment['os_name'].lower() == 'windows':
                    kernel32 = ctypes.windll.kernel32
                    c_ulong = ctypes.c_ulong
                    c_ulonglong = ctypes.c_ulonglong

                    class MEMORYSTATUS(ctypes.Structure):
                        _fields_ = [('dwLength', c_ulong),
                                    ('dwMemoryLoad', c_ulong),
                                    ('dwTotalPhys', c_ulonglong),
                                    ('dwAvailPhys', c_ulonglong),
                                    ('dwTotalPageFile', c_ulonglong),
                                    ('dwAvailPageFile', c_ulonglong),
                                    ('dwTotalVirtual', c_ulonglong),
                                    ('dwAvailVirtual', c_ulonglong),
                                    ('availExtendedVirtual', c_ulonglong)]

                    memoryStatus = MEMORYSTATUS()
                    memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
                    kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
                    environment['mem_total'] = str(
                        int(memoryStatus.dwTotalPhys) / (1024**2))
                    environment['mem_free'] = str(
                        int(memoryStatus.dwAvailPhys) / (1024**2))

                else:
                    with open('/proc/meminfo') as f:
                        meminfo = f.read()
                    environment['mem_total'] = str(
                        int(
                            re.search(r'MemTotal:\s+(\d+)',
                                      meminfo).groups()[0]) / 1024)
                    environment['mem_free'] = str(
                        int(
                            re.search(r'MemAvailable:\s+(\d+)',
                                      meminfo).groups()[0]) / 1024)
            except:
                environment['mem_total'] = ''
                environment['mem_free'] = ''

        try:
            environment['kodi_buffer'] = '20'
            environment['kodi_bmode'] = '0'
            environment['kodi_rfactor'] = '4.0'
            if filetools.exists(
                    filetools.join(xbmc.translatePath("special://userdata"),
                                   "advancedsettings.xml")):
                advancedsettings = filetools.read(
                    filetools.join(xbmc.translatePath("special://userdata"),
                                   "advancedsettings.xml")).split('\n')
                for label_a in advancedsettings:
                    if 'memorysize' in label_a:
                        environment['kodi_buffer'] = str(
                            int(
                                scrapertools.find_single_match(
                                    label_a, '>(\d+)<\/')) / 1024**2)
                    if 'buffermode' in label_a:
                        environment['kodi_bmode'] = str(
                            scrapertools.find_single_match(
                                label_a, '>(\d+)<\/'))
                    if 'readfactor' in label_a:
                        environment['kodi_rfactor'] = str(
                            scrapertools.find_single_match(
                                label_a, '>(.*?)<\/'))
        except:
            pass

        environment['userdata_path'] = str(
            xbmc.translatePath(config.get_data_path()))
        try:
            if environment['os_name'].lower() == 'windows':
                free_bytes = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(environment['userdata_path']), None, None,
                    ctypes.pointer(free_bytes))
                environment['userdata_free'] = str(
                    round(float(free_bytes.value) / (1024**3), 3))
            else:
                disk_space = os.statvfs(environment['userdata_path'])
                if not disk_space.f_frsize:
                    disk_space.f_frsize = disk_space.f_frsize.f_bsize
                environment['userdata_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
        except:
            environment['userdata_free'] = '?'

        try:
            environment['videolab_series'] = '?'
            environment['videolab_episodios'] = '?'
            environment['videolab_pelis'] = '?'
            environment['videolab_path'] = str(
                xbmc.translatePath(config.get_videolibrary_path()))
            if filetools.exists(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_tvshows"))):
                environment['videolab_series'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_tvshows")))))
                counter = 0
                for root, folders, files in filetools.walk(filetools.join(environment['videolab_path'], \
                                    config.get_setting("folder_tvshows"))):
                    for file in files:
                        if file.endswith('.strm'): counter += 1
                environment['videolab_episodios'] = str(counter)
            if filetools.exists(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_movies"))):
                environment['videolab_pelis'] = str(len(filetools.listdir(filetools.join(environment['videolab_path'], \
                                config.get_setting("folder_movies")))))
        except:
            pass
        try:
            video_updates = ['No', 'Inicio', 'Una vez', 'Inicio+Una vez']
            environment['videolab_update'] = str(
                video_updates[config.get_setting("update", "videolibrary")])
        except:
            environment['videolab_update'] = '?'
        try:
            if environment['os_name'].lower() == 'windows':
                free_bytes = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(environment['videolab_path']), None, None,
                    ctypes.pointer(free_bytes))
                environment['videolab_free'] = str(
                    round(float(free_bytes.value) / (1024**3), 3))
            else:
                disk_space = os.statvfs(environment['videolab_path'])
                if not disk_space.f_frsize:
                    disk_space.f_frsize = disk_space.f_frsize.f_bsize
                environment['videolab_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
        except:
            environment['videolab_free'] = '?'

        environment['torrentcli_name'] = ''
        environment['torrentcli_dload_path'] = ''
        environment['torrentcli_buffer'] = ''
        environment['torrentcli_dload_estrgy'] = ''
        environment['torrentcli_mem_size'] = ''
        environment['torrentcli_free'] = ''
        if config.get_setting("torrent_client", server="torrent") == 4:
            __settings__ = xbmcaddon.Addon(id="plugin.video.torrenter")
            environment['torrentcli_name'] = 'Torrenter'
            environment['torrentcli_dload_path'] = str(
                xbmc.translatePath(__settings__.getSetting('storage')))
            environment['torrentcli_buffer'] = str(
                __settings__.getSetting('pre_buffer_bytes'))
        elif config.get_setting("torrent_client", server="torrent") == 3:
            for client_torrent in ['quasar', 'elementum']:
                if xbmc.getCondVisibility(
                        'System.HasAddon("plugin.video.%s" )' %
                        client_torrent):
                    __settings__ = xbmcaddon.Addon(id="plugin.video.%s" %
                                                   client_torrent)
                    environment['torrentcli_name'] = str(client_torrent)
                    environment['torrentcli_dload_path'] = str(
                        xbmc.translatePath(
                            __settings__.getSetting('download_path')))
                    environment['torrentcli_buffer'] = str(
                        __settings__.getSetting('buffer_size'))
                    environment['torrentcli_dload_estrgy'] = str(
                        __settings__.getSetting('download_storage'))
                    environment['torrentcli_mem_size'] = str(
                        __settings__.getSetting('memory_size'))

        if environment['torrentcli_dload_path']:
            try:
                if environment['os_name'].lower() == 'windows':
                    free_bytes = ctypes.c_ulonglong(0)
                    ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                        ctypes.c_wchar_p(environment['torrentcli_dload_path']),
                        None, None, ctypes.pointer(free_bytes))
                    environment['torrentcli_free'] = str(round(float(free_bytes.value) / \
                                (1024**3), 3))
                else:
                    disk_space = os.statvfs(
                        environment['torrentcli_dload_path'])
                    if not disk_space.f_frsize:
                        disk_space.f_frsize = disk_space.f_frsize.f_bsize
                    environment['torrentcli_free'] = str(round((float(disk_space.f_bavail) / \
                                (1024**3)) * float(disk_space.f_frsize), 3))
            except:
                environment['torrentcli_free'] = '?'

        environment['proxy_active'] = ''
        try:
            proxy_channel_bloqued_str = base64.b64decode(
                config.get_setting('proxy_channel_bloqued')).decode('utf-8')
            proxy_channel_bloqued = dict()
            proxy_channel_bloqued = ast.literal_eval(proxy_channel_bloqued_str)
            for channel_bloqued, proxy_active in proxy_channel_bloqued.items():
                if proxy_active == 'ON':
                    environment['proxy_active'] += channel_bloqued + ', '
        except:
            pass
        if not environment['proxy_active']: environment['proxy_active'] = 'OFF'
        environment['proxy_active'] = environment['proxy_active'].rstrip(', ')

        for root, folders, files in filetools.walk(
                xbmc.translatePath("special://logpath/")):
            for file in files:
                if file.lower() in ['kodi.log', 'jarvis.log', 'spmc.log', 'cemc.log', \
                                'mygica.log', 'wonderbox.log', 'leiapp,log', \
                                'leianmc.log', 'kodiapp.log', 'anmc.log', \
                                'latin-anmc.log']:
                    environment['log_path'] = str(filetools.join(root, file))
                    break
            else:
                environment['log_path'] = ''
            break

        if environment['log_path']:
            environment['log_size_bytes'] = str(
                filetools.getsize(environment['log_path']))
            environment['log_size'] = str(round(float(environment['log_size_bytes']) / \
                                (1024*1024), 3))
        else:
            environment['log_size_bytes'] = ''
            environment['log_size'] = ''

        environment['debug'] = str(config.get_setting('debug'))
        environment['addon_version'] = str(config.get_addon_version())

    except:
        logger.error(traceback.format_exc())
        environment = {}
        environment['log_size'] = ''
        environment['cpu_usage'] = ''
        environment['python_version'] = ''
        environment['log_path'] = ''
        environment['userdata_free'] = ''
        environment['mem_total'] = ''
        environment['torrentcli_mem_size'] = ''
        environment['torrentcli_dload_path'] = ''
        environment['torrentcli_dload_estrgy'] = ''
        environment['machine'] = ''
        environment['platform'] = ''
        environment['torrentcli_buffer'] = ''
        environment['videolab_path'] = ''
        environment['num_version'] = ''
        environment['os_name'] = ''
        environment['torrentcli_free'] = ''
        environment['video_db'] = ''
        environment['userdata_path'] = ''
        environment['log_size_bytes'] = ''
        environment['name_version'] = ''
        environment['language'] = ''
        environment['mem_free'] = ''
        environment['prod_model'] = ''
        environment['proxy_active'] = ''
        environment['architecture'] = ''
        environment['os_release'] = ''
        environment['videolab_free'] = ''
        environment['torrentcli_name'] = ''
        environment['kodi_buffer'] = ''
        environment['kodi_bmode'] = ''
        environment['kodi_rfactor'] = ''
        environment['videolab_series'] = ''
        environment['videolab_episodios'] = ''
        environment['videolab_pelis'] = ''
        environment['videolab_update'] = ''
        environment['debug'] = ''
        environment['addon_version'] = ''

    return environment
Пример #50
0
def get_free_bytes(path):
    """Return the number of free bytes on the drive."""
    free_bytes = c_ulonglong(0)
    _GetDiskFreeSpaceExW(c_wchar_p(path), None, None, pointer(free_bytes))
    return free_bytes.value
Пример #51
0
def crypto_sign_verify_detached(sig, msg, pk):
    if None in (sig, msg, pk):
        raise ValueError
    if len(sig) != crypto_sign_BYTES:
        raise ValueError("invalid sign")
    __check(sodium.crypto_sign_verify_detached(sig, msg, ctypes.c_ulonglong(len(msg)), pk))
Пример #52
0
def _get_free_space(folder='/', unit='auto'):
    """Get the free space on the drive/folder marked by folder.  Returns a float
        of unit unit.

        folder - (optional) a string uri to a folder or drive on disk. Defaults
            to '/' ('C:' on Windows')
        unit - (optional) a string, one of ['B', 'MB', 'GB', 'TB', 'auto'].  If
            'auto', the unit returned will be automatically calculated based on
            available space.  Defaults to 'auto'.

        returns a string marking the space free and the selected unit.
        Number is rounded to two decimal places.'"""

    units = {'B': 1024, 'MB': 1024**2.0, 'GB': 1024**3.0, 'TB': 1024**4.0}

    if platform.system() == 'Windows':
        if folder == '/':
            folder = 'C:'

        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder),
                                                   None, None,
                                                   ctypes.pointer(free_bytes))
        free_space = free_bytes.value
    else:
        try:
            space = os.statvfs(folder)
        except OSError:
            # Thrown when folder does not yet exist
            # In this case, we need to take the path to the desired folder and
            # walk backwards along its directory tree until we find the mount
            # point.  This mount point is then used for statvfs.
            abspath = os.path.abspath(folder)
            while not os.path.ismount(abspath):
                abspath = os.path.dirname(abspath)
            space = os.statvfs(abspath)

        # space.f_frsize is the fundamental file system block size
        # space.f_bavail is the num. free blocks available to non-root user
        free_space = (space.f_frsize * space.f_bavail)

    # If antomatic unit detection is preferred, do it.  Otherwise, just get the
    # unit desired from the units dictionary.
    if unit == 'auto':
        units = sorted(units.iteritems(),
                       key=lambda unit: unit[1],
                       reverse=True)
        selected_unit = units[0]
        for unit, multiplier in units:
            free_unit = free_space / multiplier
            if free_unit % 1024 == free_unit:
                selected_unit = (unit, multiplier)
        factor = selected_unit[1]  # get the multiplier
        unit = selected_unit[0]
    else:
        factor = units[unit]

    # Calculate space available in desired units, rounding to 2 places.
    space_avail = round(free_space / factor, 2)

    # Format the return string.
    return str('%s %s' % (space_avail, unit))
Пример #53
0
def crypto_generichash_update(state, m):
    assert isinstance(state, CryptoGenericHashState)
    __check(sodium.crypto_generichash_update(ctypes.byref(state), m, ctypes.c_ulonglong(len(m))))
    return state
Пример #54
0
 def receiveStart(self,iw,elapsed,verbose):
     
     auxAssign = ctypes.c_ulonglong(0)
     ret = lib.taskServer_receiveStart(self.obj,iw,elapsed,
                                       ctypes.byref(auxAssign),verbose)
     return [ret,auxAssign.value]
Пример #55
0
def _validate_options(kwargs):
    opts = {k: kwargs.pop(k, OPTIONS[k]) for k in OPTIONS}
    if kwargs:
        raise TypeError("unknown keyword argument%s: %s" %
                        ("s" if len(kwargs) > 1 else "", ", ".join(
                            repr(k) for k in kwargs)))

    in_file, in_buffer = opts.pop("in_file"), opts.pop("in_buffer")
    if in_file is None and in_buffer is None:
        raise ValueError("No input file or buffer provided")
    elif in_file is not None and in_buffer is not None:
        raise ValueError("in_file and in_buffer are mutually exclusive")
    if in_file is not None:
        try:
            in_buffer = in_file.read()
        except AttributeError:
            with open(in_file, "rb") as f:
                in_buffer = f.read()
    if not isinstance(in_buffer, bytes):
        raise TypeError("in_buffer type must be bytes, not %s" %
                        type(in_buffer).__name__)
    opts['in_buffer'] = in_buffer
    opts['in_buffer_len'] = len(in_buffer)

    control_file = opts.pop('control_file')
    control_buffer = opts.pop('control_buffer')
    if control_file is not None:
        if control_buffer is not None:
            raise ValueError(
                "control_file and control_buffer are mutually exclusive")
        try:
            control_buffer = control_file.read()
        except AttributeError:
            with open(control_file, "rb") as f:
                control_buffer = f.read()
    if control_buffer is not None:
        if not isinstance(control_buffer, bytes):
            raise TypeError("control_buffer type must be bytes, not %s" %
                            type(control_buffer).__name__)
        opts['control_buffer'] = control_buffer
        opts['control_buffer_len'] = len(control_buffer)

    reference_file = opts.pop('reference_file')
    reference_buffer = opts.pop('reference_buffer')
    if reference_file is not None:
        if reference_buffer is not None:
            raise ValueError(
                "reference_file and reference_buffer are mutually exclusive")
        try:
            reference_buffer = reference_file.read()
        except AttributeError:
            with open(reference_file, "rb") as f:
                reference_buffer = f.read()
    if reference_buffer is not None:
        if not isinstance(reference_buffer, bytes):
            raise TypeError("reference_buffer type must be bytes, not %s" %
                            type(reference_buffer).__name__)
        opts['reference_buffer'] = reference_buffer
        opts['reference_buffer_len'] = len(reference_buffer)

    for key in ('reference_name', 'default_script', 'fallback_script',
                'x_height_snapping_exceptions'):
        if opts[key] is not None:
            opts[key] = tobytes(opts[key])

    if opts['epoch'] is not None:
        opts['epoch'] = c_ulonglong(epoc)

    return opts
Пример #56
0
def randombytes(size):
    buf = ctypes.create_string_buffer(size)
    sodium.randombytes(buf, ctypes.c_ulonglong(size))
    return buf.raw
Пример #57
0
 def to_host(self, ptr_host_data, begin = 0, end = -1):
     native.n_dvbufferlike_to_host(self.m_cptr, ffi.cast("void *", ptr_host_data), ctypes.c_ulonglong(begin).value, ctypes.c_ulonglong(end).value)
Пример #58
0
def crypto_generichash(m, k=b'', outlen=crypto_generichash_BYTES):
    buf = ctypes.create_string_buffer(outlen)
    __check(sodium.crypto_generichash(buf, ctypes.c_size_t(outlen), m, ctypes.c_ulonglong(len(m)), k, ctypes.c_size_t(len(k))))
    return buf.raw
Пример #59
0
 def __init__(self, func, expr_index, as_ast=True, instr_index=None):
     instr = core.BNGetHighLevelILByIndex(func.handle, expr_index, as_ast)
     self._function = func
     self._expr_index = expr_index
     if instr_index is None:
         self._instr_index = core.BNGetHighLevelILInstructionForExpr(
             func.handle, expr_index)
     else:
         self._instr_index = instr_index
     self._operation = HighLevelILOperation(instr.operation)
     self._size = instr.size
     self._address = instr.address
     self._source_operand = instr.sourceOperand
     self._parent = instr.parent
     self._as_ast = as_ast
     operands = HighLevelILInstruction.ILOperations[instr.operation]
     self._operands = []
     i = 0
     for operand in operands:
         name, operand_type = operand
         if operand_type == "int":
             value = instr.operands[i]
             value = (value & ((1 << 63) - 1)) - (value & (1 << 63))
         elif operand_type == "float":
             if instr.size == 4:
                 value = struct.unpack(
                     "f", struct.pack("I",
                                      instr.operands[i] & 0xffffffff))[0]
             elif instr.size == 8:
                 value = struct.unpack("d",
                                       struct.pack("Q",
                                                   instr.operands[i]))[0]
             else:
                 value = instr.operands[i]
         elif operand_type == "expr":
             value = HighLevelILInstruction(func, instr.operands[i],
                                            self._as_ast)
         elif operand_type == "intrinsic":
             value = lowlevelil.ILIntrinsic(func.arch, instr.operands[i])
         elif operand_type == "var":
             value = function.Variable.from_identifier(
                 self._function.source_function, instr.operands[i])
         elif operand_type == "var_ssa":
             var = function.Variable.from_identifier(
                 self._function.source_function, instr.operands[i])
             version = instr.operands[i + 1]
             i += 1
             value = mediumlevelil.SSAVariable(var, version)
         elif operand_type == "int_list":
             count = ctypes.c_ulonglong()
             operand_list = core.BNHighLevelILGetOperandList(
                 func.handle, self._expr_index, i, count)
             value = []
             for j in range(count.value):
                 value.append(operand_list[j])
             core.BNHighLevelILFreeOperandList(operand_list)
         elif operand_type == "expr_list":
             count = ctypes.c_ulonglong()
             operand_list = core.BNHighLevelILGetOperandList(
                 func.handle, self._expr_index, i, count)
             i += 1
             value = []
             for j in range(count.value):
                 value.append(
                     HighLevelILInstruction(func, operand_list[j],
                                            self._as_ast))
             core.BNHighLevelILFreeOperandList(operand_list)
         elif operand_type == "var_ssa_list":
             count = ctypes.c_ulonglong()
             operand_list = core.BNHighLevelILGetOperandList(
                 func.handle, self._expr_index, i, count)
             i += 1
             value = []
             for j in range(count.value // 2):
                 var_id = operand_list[j * 2]
                 var_version = operand_list[(j * 2) + 1]
                 value.append(
                     mediumlevelil.SSAVariable(
                         function.Variable.from_identifier(
                             self._function.source_function, var_id),
                         var_version))
             core.BNHighLevelILFreeOperandList(operand_list)
         elif operand_type == "member_index":
             value = instr.operands[i]
             if (value & (1 << 63)) != 0:
                 value = None
         elif operand_type == "label":
             value = GotoLabel(self.function, instr.operands[i])
         self._operands.append(value)
         self.__dict__[name] = value
         i += 1
Пример #60
0
 def __init__(self, val):
     MI_Value.__init__(self, MI_UINT64)
     if val is not None:
         self.value = ctypes.c_ulonglong(val)