def utf16tostr(addr, size=-1): """Read UTF-16 string from memory and encode as python string.""" cb = size if size > 0 else 32 bstr = ctypes.string_at(addr, cb) if size >= 0: return bstr.decode('utf-16le') # lookup zero char chunks = [] while True: found = cb for i in range(0, cb, 2): c = bstr[i] if c == 0x00: found = i break pass assert found % 2 == 0, "truncated string with len " + str(found) chunks.append(bstr[0:found].decode('utf-16le')) if found != cb: break addr = addr + cb bstr = ctypes.string_at(addr, cb) continue return "".join(chunks)
def inet_pton(address_family, ip_string): if sys.version_info[0] > 2 and isinstance(ip_string, bytes): raise TypeError("inet_pton() argument 2 must be str, not bytes") if address_family == socket.AF_INET: family = 2 addr = in_addr() elif address_family == socket.AF_INET6: family = 23 addr = in6_addr() else: raise OSError("unknown address family") ip_string = ctypes.c_wchar_p(ip_string) ret = InetPtonW(ctypes.c_int(family), ip_string, ctypes.byref(addr)) if ret == 1: if address_family == socket.AF_INET: return ctypes.string_at(addr.S_addr, 4) else: return ctypes.string_at(addr.Byte, 16) elif ret == 0: raise socket.error("illegal IP address string passed to inet_pton") else: err = WSAGetLastError() if err == 10047: e = socket.error("unknown address family") elif err == 10014: e = OSError("bad address") else: e = OSError("unknown error from inet_ntop") e.errno = err raise e
def encrypt(self, message, context_=None): if context_ is None: context_length_ = 0 else: context_length_ = len(context_) encrypted_message_length = c_int(0) context_length = c_int(0) if themis.themis_secure_cell_encrypt_token_protect( self.key, len(self.key), context_, context_length_, message, len(message), None, byref(context_length), None, byref(encrypted_message_length)) != -4: raise themis_exception(THEMIS_CODES.FAIL, "themis_secure_cell_encrypt_token_protect " "(encrypted message and context " "length determination) error") encrypted_message = create_string_buffer(encrypted_message_length.value) context = create_string_buffer(context_length.value) if themis.themis_secure_cell_encrypt_token_protect( self.key, len(self.key), context_, context_length_, message, len(message), context, byref(context_length), encrypted_message, byref(encrypted_message_length)) != 0: raise themis_exception(THEMIS_CODES.FAIL, "themis_secure_cell_encrypt_token_protect " "error") return (string_at(encrypted_message, encrypted_message_length.value), string_at(context, context_length))
def test_set_state(self): """set_state works as expected.""" do = rzlib.decompressobj() # change the state to a unfinished decompress data = os.urandom(1024 * 64) deflated_data = zlib.compress(data) do.decompress(deflated_data[:len(deflated_data) / 2]) new_do = rzlib.decompressobj() new_do.set_state(do.get_state()) fnames = [f[0]for f in rzlib.InflateState._fields_] code_fields = [field[0] for field in rzlib.Code._fields_] new_state = new_do._c_do.zst.state.contents old_state = do._c_do.zst.state.contents for fname in fnames: # pointers needs special care # check Code pointers if fname in ['next', 'distcode', 'lencode']: new_code = getattr(new_state, fname).contents old_code = getattr(old_state, fname).contents for f in code_fields: self.assertEqual(getattr(new_code, f), getattr(old_code, f)) continue # check the window elif fname == 'window': if new_state.write == 0 and old_state.write == 0: # the write index is 0, skip the window comparsion. continue new_window = ctypes.string_at(new_state.window, new_state.whave) old_window = ctypes.string_at(old_state.window, old_state.whave) self.assertEqual(new_window, old_window, 'not equal') continue elif fname == 'head': self.assertFalse(new_state.head) self.assertFalse(old_state.head) continue # check arrays elif fname in ['lens', 'codes', 'work']: array = getattr(new_state, fname) new_array_content = ctypes.string_at(ctypes.pointer(array), ctypes.sizeof(array)) array = getattr(new_state, fname) old_array_content = ctypes.string_at(ctypes.pointer(array), ctypes.sizeof(array)) self.assertEqual(new_array_content, old_array_content) continue # compare simple types self.assertEqual(getattr(new_state, fname), getattr(old_state, fname)) fnames = [f[0]for f in rzlib.ResumableZStream._fields_] for fname in fnames: # skip data pointers, functions and the inflate state if fname in ['next_in', 'next_out', 'zalloc', 'zfree', 'opaque', 'state']: continue self.assertEqual(getattr(new_do._c_do.zst, fname), getattr(do._c_do.zst, fname))
def readsignonDB(userpath,dbname): if libnss.NSS_Init(userpath)!=0: print """Error Initalizing NSS_Init,\n propably no usefull results""" print "Dirname: %s"%os.path.split(userpath)[-1] import sqlite3 print userpath+os.sep+dbname conn = sqlite3.connect(userpath+os.sep+dbname) c = conn.cursor() c.execute("SELECT * FROM moz_logins;") for row in c: print "--Site(%s):"%row[1] uname.data = cast(c_char_p(base64.b64decode(row[6])),c_void_p) uname.len = len(base64.b64decode(row[6])) passwd.data = cast(c_char_p(base64.b64decode(row[7])),c_void_p) passwd.len=len(base64.b64decode(row[7])) if libnss.PK11SDR_Decrypt(byref(uname),byref(dectext),byref(pwdata))==-1: errorlog(row,userpath+os.sep+dbname) print "----Username %s" % string_at(dectext.data,dectext.len) if libnss.PK11SDR_Decrypt(byref(passwd),byref(dectext),byref(pwdata))==-1: errorlog(row,userpath+os.sep+dbname) print "----Password %s" % string_at(dectext.data,dectext.len) c.close() conn.close() libnss.NSS_Shutdown()
async def die(self, ctx): """ Segfault the bot in order to kill it. """ await self.bot.say("☠") import ctypes ctypes.string_at(1)
def SetTraceVariablesList(self, idxs): """ Call ctype imported function to append these indexes to registred variables in PLC debugger """ if idxs: buff = "" # keep a copy of requested idx self._Idxs = idxs[:] for idx,iectype,force in idxs: idxstr = ctypes.string_at( ctypes.pointer( ctypes.c_uint32(idx)),4) if force !=None: c_type,unpack_func, pack_func = TypeTranslator.get(iectype, (None,None,None)) forced_type_size = ctypes.sizeof(c_type) \ if iectype != "STRING" else len(force)+1 forced_type_size_str = chr(forced_type_size) forcestr = ctypes.string_at( ctypes.pointer( pack_func(c_type,force)), forced_type_size) buff += idxstr + forced_type_size_str + forcestr else: buff += idxstr + chr(0) else: buff = "" self._Idxs = [] self.HandleSerialTransaction(SET_TRACE_VARIABLETransaction(buff))
def connect(self): self.sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) handshake_data = Handshaker(4,1,0) ctypes.string_at(ctypes.addressof(handshake_data),ctypes.sizeof(handshake_data)) self.sock.sendto(handshake_data,self.address) ac.log("Sent :-)") self.connected = True
def lastupdate(self, filename): """Get the latest update from an RRD It is basically a mini info() """ ds_time = c_time_t() ds_count = ctypes.c_ulong() ds_names = raw_char_pp() ds_values = raw_char_pp() if rrd_lastupdate_r(filename, ctypes.byref(ds_time), ctypes.byref(ds_count), ctypes.byref(ds_names), ctypes.byref(ds_values)): raise RRDLibraryError() ds_dict = OrderedDict() for i in xrange(int(ds_count.value)): name = ctypes.string_at(ds_names[i]) value = ctypes.string_at(ds_values[i]) if value == "U": value = None else: value = float(value) ds_dict[name] = value rrd_th.rrd_freemem(ds_values[i]) rrd_th.rrd_freemem(ds_names[i]) rrd_th.rrd_freemem(ds_values) rrd_th.rrd_freemem(ds_names) return ds_time.value, ds_dict
def get_tile_from_number(self, tileno, fp): """ This function does something. :param tileno: number of tile to fetch :param fp: file pointer to which tile data is written :returns: int -- the return code. :raises: AttributeError, KeyError """ # Getting a single tile tile_size = libtiff.TIFFTileSize(self.tif, tileno) #print "TileSize: ", tile_size.value if not isinstance( tile_size, ( int, long ) ): tile_size = tile_size.value tmp_tile = create_string_buffer(tile_size) r2 = libtiff.TIFFReadRawTile(self.tif, tileno, tmp_tile, tile_size) #print "Valid size in tile: ", r2.value # Experiment with the file output fp.write(ctypes.string_at(self.jpegtables, self.jpegtable_size.value)[:-2]) # Write padding padding = "%c"%(255) * 4 fp.write(padding) fp.write(ctypes.string_at(tmp_tile, r2)[2:]) if isinstance( r2, ( int, long ) ): return r2 return r2.value
def compressPNG(img, w, h, numchans): p = w*numchans z = zlib.compressobj() zbuf ="" for y in xrange(h): zbuf += z.compress("\0") zbuf += z.compress(img[y*p:y*p+p]) zbuf += z.flush() len_out = len(zbuf) pnghdr = (ctypes.c_ubyte * 41)( 0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, 0,0,w>>8,w,0,0,h>>8,h,8,ord("\0\0\04\02\06"[numchans]),0,0,0,0,0,0,0, len_out>>24,len_out>>16,len_out>>8,len_out,0x49,0x44,0x41,0x54) crc = zlib.crc32( ctypes.string_at( ctypes.byref(pnghdr,12), 17 ) ) crc = ctypes.c_uint32( _htonl( crc ) ) ctypes.memmove( ctypes.byref(pnghdr, 29), ctypes.pointer(crc), 4 ) zbuf = ctypes.string_at( pnghdr, 41 ) + zbuf crc = zlib.crc32( zbuf[41-4:] ) crc = _htonl(crc) crc = ctypes.c_int32(crc) zbuf += ctypes.string_at( ctypes.byref(crc), 4 ) footer = "\x49\x45\x4e\x44\xae\x42\x60\x82" zbuf += footer return zbuf
def xpaget(target, plist=None, n=xpa_n): buf_t = c_byte_p*n bufs = buf_t() names = buf_t() errs = buf_t() int_t = ctypes.c_int*n lens = int_t() errmsg = '' got = XPAGet(None, target, plist, None, bufs, lens, names, errs, n) if got: buf = [] for i in range(got): if lens[i]: cur = ctypes.string_at(bufs[i], lens[i]) buf.append(cur) for i in range(got): if errs[i]: errmsg += ctypes.string_at(errs[i]).strip() + '\n' else: buf = None _freebufs(bufs, n) _freebufs(names, n) _freebufs(errs, n) if errmsg: raise ValueError(errmsg) return buf
def __getitem__(self, idx): if isinstance(idx, slice): if idx.step: raise IndexError('step unsupported') return ctypes.string_at(idx.start, idx.stop-idx.start) else: return ctypes.string_at(idx, 1)
def ObjectAsBinaryString(o, schema): representation = cStringIO.StringIO() attributesByOffset = [ (off, attr) for attr, off in schema['attributeOffsets'].iteritems() ] attributesByOffset.sort() for offset, attr in attributesByOffset: representation.write(RepresentAsBinary(o[attr], schema['attributes'][attr])) if 'size' in schema: return representation.getvalue() variableAndOptionalAttributeOrder = schema['attributesWithOffsets'][:] optionalAttributesField = 0 for i in schema['optionalValueLookups']: if i in o: optionalAttributesField |= schema['optionalValueLookups'][i] else: variableAndOptionalAttributeOrder.remove(i) field = ctypes.c_uint32(optionalAttributesField) offsets = (ctypes.c_uint32 * len(variableAndOptionalAttributeOrder))() attributesWithOffsets = cStringIO.StringIO() for i, attr in enumerate(variableAndOptionalAttributeOrder): offsets[i] = attributesWithOffsets.tell() attributesWithOffsets.write(RepresentAsBinary(o[attr], schema['attributes'][attr])) representation.write(ctypes.string_at(ctypes.addressof(field), ctypes.sizeof(field))) representation.write(ctypes.string_at(ctypes.addressof(offsets), ctypes.sizeof(offsets))) representation.write(attributesWithOffsets.getvalue()) return representation.getvalue()
def sensor_callback(protocol, model, id, dataType, value, timestamp, callbackId, context): print "Sensor:", string_at(protocol), string_at(model), "id:", id if(dataType == TELLSTICK_TEMPERATURE): print "Temperature:", string_at(value), "C,", datetime.fromtimestamp(timestamp) elif(dataType == TELLSTICK_HUMIDITY): print "Humidity:", string_at(value), "%,", datetime.fromtimestamp(timestamp) print ""
def ListAsBinaryString(l, schema): representation = cStringIO.StringIO() if 'length' not in schema: listLength = len(l) count = ctypes.c_uint32(listLength) representation.write(ctypes.string_at(ctypes.addressof(count), ctypes.sizeof(count))) else: listLength = len(l) if 'fixedItemSize' in schema: for i in l: representation.write(RepresentAsBinary(i, schema['itemTypes'])) else: binaryRepresentations = [ RepresentAsBinary(i, schema['itemTypes']) for i in l ] offset = ctypes.sizeof(ctypes.c_uint32) * (listLength + 1) offsetArray = (ctypes.c_uint32 * listLength)() for i, b in enumerate(binaryRepresentations): offsetArray[i] = offset offset += len(b) representation.write(ctypes.string_at(ctypes.addressof(offsetArray), ctypes.sizeof(offsetArray))) for b in binaryRepresentations: representation.write(b) return representation.getvalue()
def _internalwrite(self,o): cp=self.fp.tell() l=len(o) self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(l)),4)) ds=[pickle.dumps(so) for so in o] ls=map(len,ds) iscompress=[0]*l for i in range(l): if (ls[i]>64): ds[i]=zlib.compress(ds[i]) ls[i]=len(ds[i]) clen=ctypes.string_at(ctypes.pointer(ctypes.c_int32(ls[i])),4) ds[i]=clen+ds[i] ls[i]+=4 iscompress[i]=1 ofa=numpy.array([0]+ls,dtype=numpy.uint32).cumsum()# compute offsets ofa+=(cp+((2+l+l)*4)) # relocate correctly for i in range(l): self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(ofa[i])),4)) self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(iscompress[i])),4)) self.fp.write(ctypes.string_at(ctypes.pointer(ctypes.c_int32(ofa[l])),4)) # write next block for i in range(len(ds)): if (self.fp.tell()!=ofa[i]): raise Exception, ("error file @ %d but declared offset at %d"%(self.fp.tell(),ofa[i])) self.fp.write(ds[i])
def initWW8(self): self.streams = {} self.gsf.gsf_init() gsfInput = self.gsf.gsf_input_memory_new(self.chars, len(self.chars), False) self.disableStderr() gsfInfile = self.gsf.gsf_infile_msole_new(gsfInput, None) self.enableStderr() if not gsfInfile: self.error = "gsf_infile_msole_new() failed" return for i in range(self.gsf.gsf_infile_num_children(gsfInfile)): child = self.gsf.gsf_infile_child_by_index(gsfInfile, i) childName = ctypes.string_at(self.gsf.gsf_infile_name_by_index(gsfInfile, i)) childSize = self.gsf.gsf_input_size(child) childData = "" while True: bufSize = 1024 pos = self.gsf.gsf_input_tell(child) if pos == childSize: break elif pos + bufSize > childSize: bufSize = childSize - pos childData += ctypes.string_at(self.gsf.gsf_input_read(child, bufSize, None), bufSize) self.streams[childName] = childData self.gsf.gsf_shutdown()
def resize_image(self, data, max_width, max_height, quality=85, crop=False, force=False): wand = self.lib.NewMagickWand() try: if not self.lib.MagickReadImageBlob(wand, data, len(data)): raise ImageException("Unsupported image format; data: %s...", binascii.b2a_hex(data[:32])) width = self.lib.MagickGetImageWidth(wand) height = self.lib.MagickGetImageHeight(wand) self.lib.MagickStripImage(wand) if crop: ratio = max(max_height * 1.0 / height, max_width * 1.0 / width) else: ratio = min(max_height * 1.0 / height, max_width * 1.0 / width) ptr = self.lib.MagickGetImageFormat(wand) src_format = ctypes.string_at(ptr).upper() self.lib.MagickRelinquishMemory(ptr) format = src_format if ratio < 1.0 or force: format = "JPEG" self.lib.MagickResizeImage( wand, int(ratio * width + 0.5), int(ratio * height + 0.5), 0, 1.0) elif format not in ("GIF", "JPEG", "PNG"): format = "JPEG" if format != src_format: # Flatten to fix background on transparent images. We have to # do this before cropping, as MagickFlattenImages appears to # drop all the crop info from that step self.lib.MagickSetImageBackgroundColor(wand, self.pixel_wand) flat_wand = self.lib.MagickFlattenImages(wand) self.lib.DestroyMagickWand(wand) wand = flat_wand if crop: x = (self.lib.MagickGetImageWidth(wand) - max_width) / 2 y = (self.lib.MagickGetImageHeight(wand) - max_height) / 2 self.lib.MagickCropImage(wand, max_width, max_height, x, y) if format == "JPEG": # Default compression is best for PNG, GIF. self.lib.MagickSetCompressionQuality(wand, quality) self.lib.MagickSetFormat(wand, format) size = ctypes.c_size_t() ptr = self.lib.MagickGetImageBlob(wand, ctypes.byref(size)) body = ctypes.string_at(ptr, size.value) self.lib.MagickRelinquishMemory(ptr) return { "data": body, "mime_type": "image/" + format.lower(), "width": self.lib.MagickGetImageWidth(wand), "height": self.lib.MagickGetImageHeight(wand), } finally: self.lib.DestroyMagickWand(wand)
def open_selector(func, title, filters = [('All Files', ('*.*',))], root = '', multi = False): ofx = OPENFILENAME(0, title, multi) lpstrFile = create_unicode_buffer(root, 1024) ofx.lpstrFile = cast(lpstrFile, c_wchar_p) newFilters = [] for filter in filters: filterTypes = ';'.join(filter[1]) newFilters.append('%s (%s)' % (filter[0], filterTypes)) newFilters.append(filterTypes) filterText = '\x00'.join(newFilters) + "\x00\x00" ofx.lpstrFilter = filterText print 'doing it' if func(ctypes.byref(ofx)): if multi: '%r' % ofx.lpstrFile print string_at(addressof(lpstrFile), 1024) offset = addressof(lpstrFile) print offset items = [] while 1: item = wstring_at(offset) offset += len(item) if item == '': break items.append(item) return items else: return ofx.lpstrFile.replace("\0", "") return ''
def __init__(self, idx, sdrtype, db): QtGui.QWidget.__init__(self) grid = QtGui.QGridLayout() self.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised) self.setLineWidth(2) self.db = db self.setLayout(grid) if sdrtype == 'RTLSDR': a=ctypes.create_string_buffer(300) b=ctypes.create_string_buffer(300) c=ctypes.create_string_buffer(300) aa=ctypes.cast(a, ctypes.POINTER(ctypes.c_ubyte)) bb=ctypes.cast(b, ctypes.POINTER(ctypes.c_ubyte)) cc=ctypes.cast(c, ctypes.POINTER(ctypes.c_ubyte)) rtlsdr.librtlsdr.rtlsdr_get_device_usb_strings(idx, aa, bb, cc) self.manufact = ctypes.string_at(aa) self.product = ctypes.string_at(bb) self.serial = ctypes.string_at(cc) defs = db.getReceiver(self.serial) if defs is not None: self.sample_rate = defs['sample_rate'] self.default = (defs['defau'] == 1) self.correction = defs['correction'] else: self.sample_rate = 2.048e6 self.default = False self.correction = 0.0 if self.default: self.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken) grid.addWidget(QtGui.QLabel("Manufacturer"), 0, 0) grid.addWidget(QtGui.QLabel(self.manufact), 0, 1) grid.addWidget(QtGui.QLabel("Product"), 1, 0) grid.addWidget(QtGui.QLabel(self.product), 1, 1) grid.addWidget(QtGui.QLabel("Serial"), 2, 0) grid.addWidget(QtGui.QLabel(self.serial), 2, 1) grid.addWidget(QtGui.QLabel("Sample Rate"), 3, 0) self.sample_rate_entry = QtGui.QLineEdit(str(self.sample_rate)) grid.addWidget(self.sample_rate_entry, 3, 1) self.sample_rate_entry.editingFinished.connect(self.entry_changed) grid.addWidget(QtGui.QLabel("Correction (ppm)"), 4, 0) self.correction_entry = QtGui.QLineEdit(str(self.correction)) grid.addWidget(self.correction_entry, 4, 1) self.correction_entry.editingFinished.connect(self.entry_changed) elif sdrtype == 'USRP': pass elif sdrtype == 'HackRF': pass else: raise Exception('Unknown sdrtype ('+str(sdrtype)+') passed to Receiver()')
def resolve(self, elf_file): if self.p_type == PT_NOTE: self.note_data = string_at(elf_file.base + self.p_offset, self.p_filesz) elif self.p_type == PT_INTERP: self.interp = string_at(elf_file.base + self.p_offset, self.p_filesz).rstrip("\0") return
def toPythonString(inString): if six.PY2: if isinstance(inString, c_char_p): return toPythonString(inString.value) return string_at(inString).rstrip() elif six.PY3: if isinstance(inString, c_char_p): return toPythonString(inString.value) return bytes.decode(string_at(inString), errors="ignore").rstrip()
def test_zcode(k=4, m=2, packet_size=1024): node = 0 # node num to be repaired # encode data_len = DATA_LENGTH print 'data len %d' % data_len encoded_data = ctypes.pointer(ctypes.c_char_p()) encoded_parity = ctypes.pointer(ctypes.c_char_p()) block_len = ctypes.c_int(1) librlc.librlc_z_encode(k, m, packet_size, orig_data, data_len, ctypes.byref(encoded_data), ctypes.byref(encoded_parity), ctypes.byref(block_len)) print 'chunk len %d' % block_len.value print 'encoded data:' r = int(pow(m, k-1)) data = ctypes.string_at(encoded_data, int(k*r*(block_len.value))) print 'len data: %d' % len(data) parity = ctypes.string_at(encoded_parity, int(m*r*(block_len.value))) print 'parity data: %d' % len(parity) encoded_data_value = data encoded_parity_value = parity librlc.librlc_z_encode_cleanup(encoded_data, encoded_parity) # decode # no decode in zcode, use original data print 'Decode: ' block_len = int(block_len.value) # repair print 'Repair: ' encoded_data = encoded_data_value encoded_parity = encoded_parity_value repair_num = (m+k-1)*r/m Alist = ctypes.c_int * repair_num repair_list = Alist() librlc.librlc_z_repair_chunk_needed(m, k, node, repair_num, repair_list) print 'repair_list ', print repair_list available_data = '' all_data = encoded_data+encoded_parity for item in repair_list: print item, available_data += all_data[block_len*item: block_len*(item+1)] out_data = ctypes.pointer(ctypes.c_char_p()) librlc.librlc_z_repair(k, m, packet_size, available_data, repair_list, repair_num, block_len, node, ctypes.byref(out_data)) data = ctypes.string_at(out_data, r*block_len) new_data = encoded_data[:(node*r)*block_len] new_data += data new_data += encoded_data[(node+1)*r*block_len:] repair_data = new_data librlc.librlc_z_repair_cleanup(out_data) eq_(repair_data, encoded_data_value)
def toPythonString(inString): if six.PY2: if isinstance(inString, c_char_p): return toPythonString(inString.value) return string_at(inString) elif six.PY3: if isinstance(inString, c_char_p): return toPythonString(inString.value) return bytes.decode(string_at(inString))
def keychain_get_credentials(account, username=''): password = '' account_domain = get_account_domain(account) password_buflen = c_uint32() password_buf = c_void_p() item = c_void_p() error = lib_security.SecKeychainFindInternetPassword( None, # keychain, NULL = default c_uint32(len(account_domain)), # server name length c_char_p(account_domain), # server name c_uint32(0), # security domain - unused None, # security domain - unused c_uint32( 0 if not username else len(username)), # account name length None if not username else c_char_p(username), # account name c_uint32(0), # path name length - unused None, # path name c_uint32(0), # port, 0 = any c_int(0), # kSecProtocolTypeAny c_int(0), # kSecAuthenticationTypeAny None, # returned password length - unused None, # returned password data - unused byref(item)) # returned keychain item reference if not error: info = SecKeychainAttributeInfo( 1, # attribute count pointer(c_uint32(1633903476)), # kSecAccountItemAttr pointer(c_uint32(6))) # CSSM_DB_ATTRIBUTE_FORMAT_BLOB attrlist_ptr = PtrSecKeychainAttributeList() error = lib_security.SecKeychainItemCopyAttributesAndData( item, # keychain item reference byref(info), # list of attributes to retrieve None, # returned item class - unused byref(attrlist_ptr), # returned attribute data byref(password_buflen), # returned password length byref(password_buf)) # returned password data if not error: try: if attrlist_ptr.contents.count == 1: attr = attrlist_ptr.contents.attr.contents username = string_at(attr.data, attr.length) password = string_at( password_buf.value, password_buflen.value) finally: lib_security.SecKeychainItemFreeAttributesAndData( attrlist_ptr, password_buf) if not username or not password: return ('', '') else: return (username, password)
def fuse_rmdir(req, inode_parent, name): '''Remove a directory''' log.debug('Handling rmdir(%d, %r)', inode_parent, string_at(name)) operations.rmdir(inode_parent, string_at(name)) log.debug('Calling fuse_reply_err(0)') try: libfuse.fuse_reply_err(req, 0) except DiscardedRequest: pass
def __cmp__(self,obj): if isinstance(obj, type(ctypes.c_void_p)): if ctypes.sizeof(obj) != len(seq): return -1 bytes = ctypes.string_at(ctypes.addressof(obj), ctypes.sizeof(obj) ) if bytes == self.seq: return 0 else: return -1 return cmp(self.seq, ctypes.string_at(ctypes.addressof(obj), ctypes.sizeof(obj) ) )
def fuse_unlink(req, parent_inode, name): '''Delete a file''' log.debug('Handling unlink(%d, %r)', parent_inode, string_at(name)) operations.unlink(parent_inode, string_at(name)) log.debug('Calling fuse_reply_err(0)') try: libfuse.fuse_reply_err(req, 0) except DiscardedRequest: pass
def fuse_removexattr(req, inode, name): '''Remove extended attribute''' log.debug('Handling removexattr(%d, %s)', inode, string_at(name)) operations.removexattr(inode, string_at(name)) log.debug('Calling fuse_reply_err(0)') try: libfuse.fuse_reply_err(req, 0) except DiscardedRequest: pass
def proc_func_expected_to_seg_fault(): if multi_worker_test_base.get_task_type() == 'worker': time.sleep(10000) ctypes.string_at(0) # Intentionally made seg fault.
def show_mem(ctypes_tuple): location = ctypes_tuple[0] size = ctypes_tuple[1] print('\nMemory reveals:') print(ctypes.string_at(location, size))
def get_string_and_free(self): res = string_at(self.data, self.size) gnutls_free_function(addressof(self.data)) self.data = None return res
def charpToString(charp): return str(ctypes.string_at(charp))
def __getitem__(self, idx): return ctypes.string_at(0)
def free_returned_char_p(result, func, cargs): retvalue = ctypes.string_at(result) p = ctypes.cast(result, ctypes.POINTER(ctypes.c_void_p)) rt.Index_Free(p) return retvalue
def parse_json_string(ptr_to_utf_8_encoded_string): return json.loads(string_at(ptr_to_utf_8_encoded_string).decode('utf-8'))
def _type2str(type_id): type_str_ptr = mjlib.mju_type2Str(type_id) if not type_str_ptr: raise Error("{!r} is not a valid object type ID.".format(type_id)) return ctypes.string_at(type_str_ptr)
def free_error_msg_ptr(result, func, cargs): retvalue = ctypes.string_at(result) p = ctypes.cast(result, ctypes.POINTER(ctypes.c_void_p)) rt.Index_Free(p) return retvalue
def name(self): """Returns the name of the model.""" # The model name is the first null-terminated string in the `names` buffer. return util.to_native_string( ctypes.string_at(ctypes.addressof(self.names.contents)))
def NEWBUF_test_newbuf(self): from ctypes import string_at buftools = self.buftools Exporter = buftools.Exporter Importer = buftools.Importer exp = Exporter((10, ), 'B', readonly=True) b = BufferProxy(exp) self.assertEqual(b.length, exp.len) self.assertEqual(b.raw, string_at(exp.buf, exp.len)) d = b.__array_interface__ try: self.assertEqual(d['typestr'], '|u1') self.assertEqual(d['shape'], exp.shape) self.assertEqual(d['strides'], exp.strides) self.assertEqual(d['data'], (exp.buf, True)) finally: d = None exp = Exporter((3, ), '=h') b = BufferProxy(exp) self.assertEqual(b.length, exp.len) self.assertEqual(b.raw, string_at(exp.buf, exp.len)) d = b.__array_interface__ try: lil_endian = pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN f = '{}i{}'.format('<' if lil_endian else '>', exp.itemsize) self.assertEqual(d['typestr'], f) self.assertEqual(d['shape'], exp.shape) self.assertEqual(d['strides'], exp.strides) self.assertEqual(d['data'], (exp.buf, False)) finally: d = None exp = Exporter((10, 2), '=i') b = BufferProxy(exp) imp = Importer(b, buftools.PyBUF_RECORDS) self.assertTrue(imp.obj is b) self.assertEqual(imp.buf, exp.buf) self.assertEqual(imp.ndim, exp.ndim) self.assertEqual(imp.format, exp.format) self.assertEqual(imp.readonly, exp.readonly) self.assertEqual(imp.itemsize, exp.itemsize) self.assertEqual(imp.len, exp.len) self.assertEqual(imp.shape, exp.shape) self.assertEqual(imp.strides, exp.strides) self.assertTrue(imp.suboffsets is None) d = { 'typestr': '|u1', 'shape': (10, ), 'strides': (1, ), 'data': (9, True) } # 9? Will not reading the data anyway. b = BufferProxy(d) imp = Importer(b, buftools.PyBUF_SIMPLE) self.assertTrue(imp.obj is b) self.assertEqual(imp.buf, 9) self.assertEqual(imp.len, 10) self.assertEqual(imp.format, None) self.assertEqual(imp.itemsize, 1) self.assertEqual(imp.ndim, 0) self.assertTrue(imp.readonly) self.assertTrue(imp.shape is None) self.assertTrue(imp.strides is None) self.assertTrue(imp.suboffsets is None)
def OnWSMessageBodyWarp(self, Sender, ConnID, Data, Length): return self.OnWSMessageBody(Sender=Sender, ConnID=ConnID, Data=ctypes.string_at(Data, Length))
def __str__(self): return ctypes.string_at(self.buf, self.size)
def toctype(val, btype=ctypes.c_float): a = (btype * len(val))(*val) return ctypes.string_at(a, ctypes.sizeof(a))
C_EMPTY = CFUNCTYPE(c_int, c_void_p) C_INT = CFUNCTYPE(c_int, c_void_p, c_int) C_LONG = CFUNCTYPE(c_int, c_void_p, c_long) C_DOUBLE = CFUNCTYPE(c_int, c_void_p, c_double) C_STR = CFUNCTYPE(c_int, c_void_p, POINTER(c_ubyte), c_uint) _callback_data = [ # Mapping of JSON parser events to callback C types and value converters. # Used to define the Callbacks structure and actual callback functions # inside the parse function. ('null', C_EMPTY, lambda: 'null'), ('boolean', C_INT, lambda v: 'true' if v else 'false'), # "integer" and "double" aren't actually yielded by yajl since "number" # takes precedence if defined ('integer', C_LONG, lambda v, l: string_at(v, l)), ('double', C_DOUBLE, lambda v, l: string_at(v, l)), ('number', C_STR, lambda v, l: b2s(string_at(v, l))), ('string', C_STR, lambda v, l: string_at(v, l).decode('utf-8')), ('start_map', C_EMPTY, lambda: None), ('map_key', C_STR, lambda v, l: b2s(string_at(v, l))), ('end_map', C_EMPTY, lambda: None), ('start_array', C_EMPTY, lambda: None), ('end_array', C_EMPTY, lambda: None), ] class Callbacks(Structure): _fields_ = [(name, type) for name, type, func in _callback_data] YAJL_OK = 0 YAJL_CANCELLED = 1
def processing(self, samples, count): data = string_at(samples, count * self.SAMPLE_WIDTH) if self._wave: self._wave.writeframesraw(data) else: self._stream.put(data)
def getUserInfo(self): p = dll.GetUserInfo(self.user, self.pwd) if p: return ctypes.string_at(p, -1).decode() return ''
def _OnSyncSetKeyValueCb(storageObj, key: str, value, size): storageObj.SetSdkKey(key.decode("utf-8"), ctypes.string_at(value, size))
def do_segfault(): # https://codegolf.stackexchange.com/questions/4399 # /shortest-code-that-raises-a-sigsegv print('[do_segfault] bye bye !!') ctypes.string_at(0) # segmentation fault
def Pack(ctype_instance): buf = toHex( ctypes.string_at(ctypes.byref(ctype_instance), ctypes.sizeof(ctype_instance))) return buf
def _read_bytes(self, vaddr, size): laddr = self._vtop(vaddr) #data = b''.join([ struct.pack('B',x) for x in self.readArray( vaddr, ctypes.c_ubyte, size) ] ) data = ctypes.string_at(laddr, size) # real 0.5 % perf return data
def __bytes__(self): return ctypes.string_at(self.context, self.size)
def proc_func_expected_to_seg_fault(): ctypes.string_at(0) # Intentionally made seg fault.
def detect(self, img, estimate_tag_pose=False, camera_params=None, tag_size=None): '''Run detectons on the provided image. The image must be a grayscale image of type numpy.uint8.''' assert len(img.shape) == 2 assert img.dtype == numpy.uint8 c_img = self._convert_image(img) return_info = [] #detect apriltags in the image self.libc.apriltag_detector_detect.restype = ctypes.POINTER(_ZArray) detections = self.libc.apriltag_detector_detect(self.tag_detector_ptr, c_img) apriltag = ctypes.POINTER(_ApriltagDetection)() for i in range(0, detections.contents.size): #extract the data for each apriltag that was identified zarray_get(detections, i, ctypes.byref(apriltag)) tag = apriltag.contents homography = _matd_get_array(tag.H).copy() # numpy.zeros((3,3)) # Don't ask questions, move on with your life center = numpy.ctypeslib.as_array(tag.c, shape=(2,)).copy() corners = numpy.ctypeslib.as_array(tag.p, shape=(4, 2)).copy() detection = Detection() detection.tag_family = ctypes.string_at(tag.family.contents.name) detection.tag_id = tag.id detection.hamming = tag.hamming detection.decision_margin = tag.decision_margin detection.homography = homography detection.center = center detection.corners = corners if estimate_tag_pose: if camera_params==None: raise Exception('camera_params must be provided to detect if estimate_tag_pose is set to True') if tag_size==None: raise Exception('tag_size must be provided to detect if estimate_tag_pose is set to True') camera_fx, camera_fy, camera_cx, camera_cy = [ c for c in camera_params ] info = _ApriltagDetectionInfo(det=apriltag, tagsize=tag_size, fx=camera_fx, fy=camera_fy, cx=camera_cx, cy=camera_cy) pose = _ApriltagPose() self.libc.estimate_tag_pose.restype = ctypes.c_double err = self.libc.estimate_tag_pose(ctypes.byref(info), ctypes.byref(pose)) detection.pose_R = _matd_get_array(pose.R).copy() detection.pose_t = _matd_get_array(pose.t).copy() detection.pose_err = err #Append this dict to the tag data array return_info.append(detection) self.libc.image_u8_destroy.restype = None self.libc.image_u8_destroy(c_img) self.libc.apriltag_detections_destroy.restype = None self.libc.apriltag_detections_destroy(detections) return return_info
def GetPalette(dib): bpp = _dll.FreeImage_GetBPP(dib) if bpp not in [1, 4, 8]: raise Error('Unsupported bit depth for palette') ptr = _dll.FreeImage_GetPalette(dib) return ctypes.string_at(ptr, 1 << (bpp + 2))
def log_callback(sev, buf, len): self.log(sev, ctypes.string_at(buf, len).decode('utf-16'))
def OnOperationalCredentialsRequested(csr, csr_length): GetCommissioner()._OnOperationalCredentialsRequested(ctypes.string_at(csr, csr_length))
def to_read_bytes(self): return string_at(self.read_buf, sizeof(self.read_buf))
def _checkError(err): if bool(err): # Not an empty null-terminated string message = ctypes.string_at(err) ldb.leveldb_free(ctypes.cast(err, ctypes.c_void_p)) raise Exception(message)
def BoolAsBinaryStringWithIndexedOffsetData(v, schema, path): r = ctypes.c_ubyte(255 if v else 0) return (ctypes.string_at(ctypes.addressof(r), ctypes.sizeof(r)), IndexedOffsetData())