Ejemplo n.º 1
0
func (self *KcDb) Iter(fun func(string, Getter) bool) {
	cur := C.kcdbcursor(self.cdb)
	C.kccurjump(cur)
	var kSize, vSize C.size_t
	var vBuff, kBuff *C.char
	var ret bool
	for {
		kBuff = C.kccurget(cur, &kSize, &vBuff, &vSize, kcTrue)
		if kBuff == nil {
			C.kcfree(unsafe.Pointer(kBuff))
			break
		}
		key := string(C.GoBytes(unsafe.Pointer(kBuff), C.int(kSize)))
		value := C.GoBytes(unsafe.Pointer(vBuff), C.int(vSize))
		r := bytes.NewReader(value)
		ret = fun(key, func(e interface{}) error {
			return decode(r, e)
		})
		C.kcfree(unsafe.Pointer(kBuff))
		if ret == false {
			break
		}
	}
	C.kccurdel(cur)
}
Ejemplo n.º 2
0
//export GetProof
func GetProof(dispatcher_c unsafe.Pointer, server_ip_c unsafe.Pointer, server_ip_sz C.size_t, hostname_c unsafe.Pointer, hostname_sz_c C.size_t, server_config_c unsafe.Pointer, server_config_sz_c C.size_t, ecdsa_ok_c C.int, out_certs_c ***C.char, out_certs_sz_c *C.int, out_certs_item_sz_c **C.size_t, out_signature_c **C.char, out_signature_sz_c *C.size_t) C.int {
	dispatcher := (*QuicDispatcher)(dispatcher_c)

	if !dispatcher.isSecure {
		return C.int(0)
	}

	serverIp := net.IP(C.GoBytes(server_ip_c, C.int(server_ip_sz)))
	hostname := C.GoBytes(hostname_c, C.int(hostname_sz_c))
	serverConfig := C.GoBytes(server_config_c, C.int(server_config_sz_c))
	ecdsaOk := int(ecdsa_ok_c) > 0

	certs, sig := dispatcher.proofSource.GetProof(serverIp, hostname, serverConfig, ecdsaOk)
	certsCStrList := make([](*C.char), 0, 10)
	certsCStrSzList := make([](C.size_t), 0, 10)
	for _, outCert := range certs {
		outCert_c := C.CString(string(outCert)) // Must free this C string in C code
		certsCStrList = append(certsCStrList, outCert_c)
		certsCStrSzList = append(certsCStrSzList, C.size_t(len(outCert)))
	}

	*out_certs_c = (**C.char)(unsafe.Pointer(&certsCStrList[0]))
	*out_certs_sz_c = C.int(len(certsCStrList))
	*out_certs_item_sz_c = (*C.size_t)(unsafe.Pointer(&certsCStrSzList[0]))
	*out_signature_c = C.CString(string(sig)) // Must free C string
	*out_signature_sz_c = C.size_t(len(sig))

	return C.int(1)
}
Ejemplo n.º 3
0
//export registeredCB
func registeredCB(
	ptr unsafe.Pointer,
	frameworkMessage *C.ProtobufObj,
	masterMessage *C.ProtobufObj) {
	if ptr != nil {
		var driver *SchedulerDriver = (*SchedulerDriver)(ptr)

		if driver.Scheduler.Registered == nil {
			return
		}

		frameworkData := C.GoBytes(
			frameworkMessage.data,
			C.int(frameworkMessage.size))

		var frameworkId FrameworkID
		err := proto.Unmarshal(frameworkData, &frameworkId)
		if err != nil {
			return
		}

		masterData := C.GoBytes(masterMessage.data, C.int(masterMessage.size))
		var masterInfo MasterInfo
		err = proto.Unmarshal(masterData, &masterInfo)
		if err != nil {
			return
		}

		driver.Scheduler.Registered(driver, frameworkId, masterInfo)
	}
}
Ejemplo n.º 4
0
// Render returns the map as an encoded image.
func (m *Map) Render(opts RenderOpts) ([]byte, error) {
	scaleFactor := opts.ScaleFactor
	if scaleFactor == 0.0 {
		scaleFactor = 1.0
	}
	i := C.mapnik_map_render_to_image(m.m, C.double(opts.Scale), C.double(scaleFactor))
	if i == nil {
		return nil, m.lastError()
	}
	defer C.mapnik_image_free(i)
	if opts.Format == "raw" {
		size := 0
		raw := C.mapnik_image_to_raw(i, (*C.size_t)(unsafe.Pointer(&size)))
		return C.GoBytes(unsafe.Pointer(raw), C.int(size)), nil
	}
	var format *C.char
	if opts.Format != "" {
		format = C.CString(opts.Format)
	} else {
		format = C.CString("png256")
	}
	b := C.mapnik_image_to_blob(i, format)
	if b == nil {
		return nil, errors.New("mapnik: " + C.GoString(C.mapnik_image_last_error(i)))
	}
	C.free(unsafe.Pointer(format))
	defer C.mapnik_image_blob_free(b)
	return C.GoBytes(unsafe.Pointer(b.ptr), C.int(b.len)), nil
}
Ejemplo n.º 5
0
Archivo: tpm.go Proyecto: krnowak/rkt
// GetEventLog returns an array of structures representing the contents of the
// TSS event log
func (tpm *TPM) GetEventLog() ([]Log, error) {
	var count C.UINT32
	var events *C.TSS_PCR_EVENT
	var event C.TSS_PCR_EVENT

	err := tspiError(C.Tspi_TPM_GetEventLog(tpm.handle, &count, &events))
	if err != nil {
		return nil, err
	}

	if count == 0 {
		return nil, nil
	}

	log := make([]Log, count)
	length := count * C.UINT32(unsafe.Sizeof(event))
	slice := (*[1 << 30]C.TSS_PCR_EVENT)(unsafe.Pointer(events))[:length:length]

	for i := 0; i < int(count); i++ {
		log[i].Pcr = int(slice[i].ulPcrIndex)
		log[i].Eventtype = int(slice[i].eventType)
		log[i].PcrValue = C.GoBytes(unsafe.Pointer(slice[i].rgbPcrValue), C.int(slice[i].ulPcrValueLength))
		log[i].Event = C.GoBytes(unsafe.Pointer(slice[i].rgbEvent), C.int(slice[i].ulEventLength))
	}
	C.Tspi_Context_FreeMemory(tpm.context, (*C.BYTE)(unsafe.Pointer(events)))
	return log, nil
}
Ejemplo n.º 6
0
Archivo: lsm.go Proyecto: reusee/obox
func (self *LsmDb) Iter(fun func(string, Getter) bool) {
	var cur *C.lsm_cursor
	rc := C.lsm_csr_open(self.cdb, &cur)
	if rc != C.LSM_OK {
		return
	}
	defer C.lsm_csr_close(cur)
	var keyP, valP unsafe.Pointer
	var keyL, valL C.int
	for rc := C.lsm_csr_first(cur); rc == C.LSM_OK && C.lsm_csr_valid(cur) == lsmTrue; rc = C.lsm_csr_next(cur) {
		rc = C.lsm_csr_key(cur, &keyP, &keyL)
		if rc != C.LSM_OK {
			break
		}
		rc = C.lsm_csr_value(cur, &valP, &valL)
		if rc != C.LSM_OK {
			break
		}
		key := string(C.GoBytes(keyP, keyL))
		value := C.GoBytes(valP, valL)
		r := bytes.NewReader(value)
		ret := fun(key, func(obj interface{}) error {
			return decode(r, obj)
		})
		if ret == false {
			break
		}
	}
}
Ejemplo n.º 7
0
//export consume
func consume(ctx *C.knot_layer_t, pkt *C.knot_pkt_t) C.int {
	req := (*C.struct_kr_request)(ctx.data)
	qry := req.current_query
	state := (C.int)(ctx.state)
	if qry.flags&C.QUERY_CACHED != 0 {
		return state
	}
	// Parse answer source address
	sa := (*C.struct_sockaddr)(unsafe.Pointer(&qry.ns.addr[0]))
	var ip net.IP
	if sa.sa_family == C.AF_INET {
		sa_v4 := (*C.struct_sockaddr_in)(unsafe.Pointer(sa))
		ip = net.IP(C.GoBytes(unsafe.Pointer(&sa_v4.sin_addr), 4))
	} else if sa.sa_family == C.AF_INET6 {
		sa_v6 := (*C.struct_sockaddr_in6)(unsafe.Pointer(sa))
		ip = net.IP(C.GoBytes(unsafe.Pointer(&sa_v6.sin6_addr), 16))
	}
	// Parse metadata
	qname := C.knot_dname_to_str_alloc(C.knot_pkt_qname(pkt))
	defer C.free(unsafe.Pointer(qname))
	qtype := C.knot_pkt_qtype(pkt)
	secure := (bool)(C.knot_pkt_has_dnssec(pkt))
	// Sample metric
	process_sample(C.GoString(qname), int(qtype), ip, secure)
	return state
}
Ejemplo n.º 8
0
func (cursor *Cursor) Get(set_key []byte, op uint) (key, val []byte, err error) {
	var ckey C.MDB_val
	var cval C.MDB_val
	if set_key != nil && op == SET {
		var cset_key *C.MDB_val
		cset_key = &C.MDB_val{mv_size: C.size_t(len(set_key)),
			mv_data: unsafe.Pointer(&set_key[0])}
		ret := C.mdb_cursor_get(cursor._cursor, cset_key, &cval, C.MDB_cursor_op(op))
		if ret != SUCCESS {
			err = Errno(ret)
			key = nil
			val = nil
			return
		}
		key = set_key
		val = C.GoBytes(cval.mv_data, C.int(cval.mv_size))
	}
	ret := C.mdb_cursor_get(cursor._cursor, &ckey, &cval, C.MDB_cursor_op(op))
	if ret != SUCCESS {
		err = Errno(ret)
		key = nil
		val = nil
		return
	}
	err = nil
	key = C.GoBytes(ckey.mv_data, C.int(ckey.mv_size))
	val = C.GoBytes(cval.mv_data, C.int(cval.mv_size))
	return
}
Ejemplo n.º 9
0
func loadSystemRoots() (*CertPool, error) {
	roots := NewCertPool()

	var data C.CFDataRef = nil
	var untrustedData C.CFDataRef = nil
	err := C.FetchPEMRoots(&data, &untrustedData)
	if err == -1 {
		// TODO: better error message
		return nil, errors.New("crypto/x509: failed to load darwin system roots with cgo")
	}

	defer C.CFRelease(C.CFTypeRef(data))
	buf := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data)))
	roots.AppendCertsFromPEM(buf)
	if untrustedData == nil {
		return roots, nil
	}
	defer C.CFRelease(C.CFTypeRef(untrustedData))
	buf = C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(untrustedData)), C.int(C.CFDataGetLength(untrustedData)))
	untrustedRoots := NewCertPool()
	untrustedRoots.AppendCertsFromPEM(buf)

	trustedRoots := NewCertPool()
	for _, c := range roots.certs {
		if !untrustedRoots.contains(c) {
			trustedRoots.AddCert(c)
		}
	}
	return trustedRoots, nil
}
Ejemplo n.º 10
0
// GetTokenInfo obtains information about a particular token
// in the system.
func (c *Ctx) GetTokenInfo(slotID uint) (TokenInfo, error) {
	var cti C.CK_TOKEN_INFO
	e := C.GetTokenInfo(c.ctx, C.CK_ULONG(slotID), &cti)
	s := TokenInfo{
		Label:              strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.label[0]), 32)), " "),
		ManufacturerID:     strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.manufacturerID[0]), 32)), " "),
		Model:              strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.model[0]), 16)), " "),
		SerialNumber:       strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.serialNumber[0]), 16)), " "),
		Flags:              uint(cti.flags),
		MaxSessionCount:    uint(cti.ulMaxSessionCount),
		SessionCount:       uint(cti.ulSessionCount),
		MaxRwSessionCount:  uint(cti.ulMaxRwSessionCount),
		RwSessionCount:     uint(cti.ulRwSessionCount),
		MaxPinLen:          uint(cti.ulMaxPinLen),
		MinPinLen:          uint(cti.ulMinPinLen),
		TotalPublicMemory:  uint(cti.ulTotalPublicMemory),
		FreePublicMemory:   uint(cti.ulFreePublicMemory),
		TotalPrivateMemory: uint(cti.ulTotalPrivateMemory),
		FreePrivateMemory:  uint(cti.ulFreePrivateMemory),
		HardwareVersion:    toVersion(cti.hardwareVersion),
		FirmwareVersion:    toVersion(cti.firmwareVersion),
		UTCTime:            strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&cti.utcTime[0]), 16)), " "),
	}
	return s, toError(e)
}
Ejemplo n.º 11
0
//export GetProof
func GetProof(proof_source_c unsafe.Pointer, server_ip_c unsafe.Pointer, server_ip_sz C.size_t, hostname_c unsafe.Pointer, hostname_sz_c C.size_t, server_config_c unsafe.Pointer, server_config_sz_c C.size_t, ecdsa_ok_c C.int, out_certs_c ***C.char, out_certs_sz_c *C.int, out_certs_item_sz_c **C.size_t, out_signature_c **C.char, out_signature_sz_c *C.size_t) C.int {
	proofSource := (*ProofSource)(proof_source_c)
	if !proofSource.impl.IsSecure() {
		return C.int(0)
	}

	serverIp := net.IP(C.GoBytes(server_ip_c, C.int(server_ip_sz)))
	hostname := C.GoBytes(hostname_c, C.int(hostname_sz_c))
	serverConfig := C.GoBytes(server_config_c, C.int(server_config_sz_c))
	ecdsaOk := int(ecdsa_ok_c) > 0

	certs, sig := proofSource.impl.GetProof(serverIp, hostname, serverConfig, ecdsaOk)
	certsCStrList := make([](*C.char), 0, 10)
	certsCStrSzList := make([](C.size_t), 0, 10)

	// XXX(hodduc): certsCStrList and certsCStrSzList may be garbage collected before reading in C side, isn't it?

	for _, outCert := range certs {
		outCert_c := C.CString(string(outCert)) // Must free this C string in C code
		certsCStrList = append(certsCStrList, outCert_c)
		certsCStrSzList = append(certsCStrSzList, C.size_t(len(outCert)))
	}

	*out_certs_c = (**C.char)(unsafe.Pointer(&certsCStrList[0]))
	*out_certs_sz_c = C.int(len(certsCStrList))
	*out_certs_item_sz_c = (*C.size_t)(unsafe.Pointer(&certsCStrSzList[0]))
	*out_signature_c = C.CString(string(sig)) // Must free C string
	*out_signature_sz_c = C.size_t(len(sig))

	return C.int(1)
}
Ejemplo n.º 12
0
//export executorLostCB
func executorLostCB(
	ptr unsafe.Pointer,
	executorIdMessage *C.ProtobufObj,
	slaveIdMessage *C.ProtobufObj,
	status C.int) {
	if ptr != nil {
		var driver *SchedulerDriver = (*SchedulerDriver)(ptr)
		if driver.Scheduler.ExecutorLost == nil {
			return
		}

		executorData := C.GoBytes(executorIdMessage.data, C.int(executorIdMessage.size))
		var executorId ExecutorID
		err := proto.Unmarshal(executorData, &executorId)
		if err != nil {
			return
		}

		slaveData := C.GoBytes(slaveIdMessage.data, C.int(slaveIdMessage.size))
		var slaveId SlaveID
		err = proto.Unmarshal(slaveData, &slaveId)
		if err != nil {
			return
		}

		driver.Scheduler.ExecutorLost(driver, executorId, slaveId, int(status))
	}
}
Ejemplo n.º 13
0
//export frameworkMessageCB
func frameworkMessageCB(
	ptr unsafe.Pointer,
	executorIdMessage *C.ProtobufObj,
	slaveIdMessage *C.ProtobufObj,
	dataMessage *C.ProtobufObj) {
	if ptr != nil {
		var driver *SchedulerDriver = (*SchedulerDriver)(ptr)
		if driver.Scheduler.FrameworkMessage == nil {
			return
		}
		executorData := C.GoBytes(executorIdMessage.data, C.int(executorIdMessage.size))
		var executorId ExecutorID
		err := proto.Unmarshal(executorData, &executorId)
		if err != nil {
			return
		}

		slaveData := C.GoBytes(slaveIdMessage.data, C.int(slaveIdMessage.size))
		var slaveId SlaveID
		err = proto.Unmarshal(slaveData, &slaveId)
		if err != nil {
			return
		}

		message := C.GoBytes(dataMessage.data, C.int(dataMessage.size))
		var messageString string = string(message)

		driver.Scheduler.FrameworkMessage(driver, executorId, slaveId, messageString)
	}
}
Ejemplo n.º 14
0
Archivo: cursor.go Proyecto: raff/bolt
// Next moves the cursor to the next element and returns the key and value.
// Returns a nil key if there are no more key/value pairs.
func (c *Cursor) Next() (key, value []byte) {
	var k, v C.bolt_val
	var flags C.uint32_t
	C.bolt_cursor_next(c.C, &k, &v, &flags)
	if k.data == nil {
		return nil, nil
	}
	return C.GoBytes(k.data, C.int(k.size)), C.GoBytes(v.data, C.int(v.size))
}
Ejemplo n.º 15
0
// Resolve wraps Unbound's ub_resolve.
func (u *Unbound) Resolve(name string, rrtype, rrclass uint16) (*Result, error) {
	res := C.new_ub_result()
	r := new(Result)
	defer C.ub_resolve_free(res)
	i := C.ub_resolve(u.ctx, C.CString(name), C.int(rrtype), C.int(rrclass), &res)
	err := newError(int(i))
	if err != nil {
		return nil, err
	}

	r.Qname = C.GoString(res.qname)
	r.Qtype = uint16(res.qtype)
	r.Qclass = uint16(res.qclass)

	r.CanonName = C.GoString(res.canonname)
	r.Rcode = int(res.rcode)
	r.AnswerPacket = new(dns.Msg)
	r.AnswerPacket.Unpack(C.GoBytes(res.answer_packet, res.answer_len)) // Should always work
	r.HaveData = res.havedata == 1
	r.NxDomain = res.nxdomain == 1
	r.Secure = res.secure == 1
	r.Bogus = res.bogus == 1
	r.WhyBogus = C.GoString(res.why_bogus)

	// Re-create the RRs
	var h dns.RR_Header
	h.Name = r.Qname
	h.Rrtype = r.Qtype
	h.Class = r.Qclass
	h.Ttl = 0

	r.Data = make([][]byte, 0)
	r.Rr = make([]dns.RR, 0)
	j := 0
	if r.HaveData {
		b := C.GoBytes(unsafe.Pointer(C.array_elem_char(res.data, C.int(j))), C.array_elem_int(res.len, C.int(j)))
		for len(b) != 0 {
			// Create the RR
			h.Rdlength = uint16(len(b))
			msg := make([]byte, 20+len(h.Name)) // Long enough
			off, _ := dns.PackStruct(&h, msg, 0)
			msg = msg[:off]
			rrbuf := append(msg, b...)
			rr, _, err := dns.UnpackRR(rrbuf, 0)
			if err == nil {
				r.Rr = append(r.Rr, rr)
			}

			r.Data = append(r.Data, b)
			j++
			b = C.GoBytes(unsafe.Pointer(C.array_elem_char(res.data, C.int(j))), C.array_elem_int(res.len, C.int(j)))

		}
	}
	return r, err
}
Ejemplo n.º 16
0
//export merge
// merge is a wrapper around goMerge, returning the result
// as a non-garbage collected C string.
// It is used by C code in this package.
func merge(a, b *C.char, aLen, bLen C.size_t) (*C.char, C.size_t) {
	result, err := goMerge(C.GoBytes(unsafe.Pointer(a), C.int(aLen)),
		C.GoBytes(unsafe.Pointer(b), C.int(bLen)))
	if err != nil {
		return nil, 0
	}
	// As above, the first return value will have to be manually freed
	// by the receiver.
	return C.CString(string(result)), C.size_t(len(result))
}
Ejemplo n.º 17
0
func webpSetMetadata(data, metadata []byte, format string) (newData []byte, err error) {
	if len(data) == 0 || len(metadata) == 0 {
		err = errors.New("webpSetMetadata: bad arguments")
		return
	}
	isCBuf := false
	cData := cgoSafePtr(data, isCBuf)
	defer cgoFreePtr(cData, isCBuf)
	cMetadata := cgoSafePtr(metadata, isCBuf)
	defer cgoFreePtr(cMetadata, isCBuf)

	switch format {
	case "EXIF":
		rv := C.cgoWebpSetEXIF(
			(*C.uint8_t)(cData), C.size_t(len(data)),
			(*C.char)(cMetadata), C.size_t(len(metadata)),
		)
		if rv.ok != 1 {
			err = errors.New("webpSetMetadata: failed")
			return
		}
		newData = C.GoBytes(unsafe.Pointer(rv.ptr), C.int(rv.size))
		C.webpFree(unsafe.Pointer(rv.ptr))
		return
	case "ICCP":
		rv := C.cgoWebpSetICCP(
			(*C.uint8_t)(cData), C.size_t(len(data)),
			(*C.char)(cMetadata), C.size_t(len(metadata)),
		)
		if rv.ok != 1 {
			err = errors.New("webpSetMetadata: failed")
			return
		}
		newData = C.GoBytes(unsafe.Pointer(rv.ptr), C.int(rv.size))
		C.webpFree(unsafe.Pointer(rv.ptr))
		return
	case "XMP":
		rv := C.cgoWebpSetXMP(
			(*C.uint8_t)(cData), C.size_t(len(data)),
			(*C.char)(cMetadata), C.size_t(len(metadata)),
		)
		if rv.ok != 1 {
			err = errors.New("webpSetMetadata: failed")
			return
		}
		newData = C.GoBytes(unsafe.Pointer(rv.ptr), C.int(rv.size))
		C.webpFree(unsafe.Pointer(rv.ptr))
		return
	default:
		err = errors.New("webpSetMetadata: unknown format")
		return
	}
}
Ejemplo n.º 18
0
/* GetSlotInfo obtains information about a particular slot in the system. */
func (c *Ctx) GetSlotInfo(slotID uint) (SlotInfo, error) {
	var csi C.CK_SLOT_INFO
	e := C.GetSlotInfo(c.ctx, C.CK_ULONG(slotID), &csi)
	s := SlotInfo{
		SlotDescription: strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&csi.slotDescription[0]), 64)), " "),
		ManufacturerID:  strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&csi.manufacturerID[0]), 32)), " "),
		Flags:           uint(csi.flags),
		HardwareVersion: toVersion(csi.hardwareVersion),
		FirmwareVersion: toVersion(csi.firmwareVersion),
	}
	return s, toError(e)
}
Ejemplo n.º 19
0
/* GetInfo returns general information about Cryptoki. */
func (c *Ctx) GetInfo() (Info, error) {
	var p C.CK_INFO
	e := C.GetInfo(c.ctx, C.CK_INFO_PTR(&p))
	i := Info{
		CryptokiVersion:    toVersion(p.cryptokiVersion),
		ManufacturerID:     strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&p.manufacturerID[0]), 32)), " "),
		Flags:              uint(p.flags),
		LibraryDescription: strings.TrimRight(string(C.GoBytes(unsafe.Pointer(&p.libraryDescription[0]), 32)), " "),
		LibraryVersion:     toVersion(p.libraryVersion),
	}
	return i, toError(e)
}
Ejemplo n.º 20
0
// Scan returns up to max key/value objects starting from
// start (inclusive) and ending at end (non-inclusive).
// If max is zero then the number of key/values returned is unbounded.
func (r *RocksDB) Scan(start, end Key, max int64) ([]RawKeyValue, error) {
	var keyVals []RawKeyValue
	if bytes.Compare(start, end) >= 0 {
		return keyVals, nil
	}
	// In order to prevent content displacement, caching is disabled
	// when performing scans. Any options set within the shared read
	// options field that should be carried over needs to be set here
	// as well.
	opts := C.rocksdb_readoptions_create()
	C.rocksdb_readoptions_set_fill_cache(opts, 0)
	defer C.rocksdb_readoptions_destroy(opts)
	it := C.rocksdb_create_iterator(r.rdb, opts)
	defer C.rocksdb_iter_destroy(it)

	byteCount := len(start)
	if byteCount == 0 {
		// start=Key("") needs special treatment since we need
		// to access start[0] in an explicit seek.
		C.rocksdb_iter_seek_to_first(it)
	} else {
		C.rocksdb_iter_seek(it, bytesPointer(start), C.size_t(byteCount))
	}
	for i := int64(1); C.rocksdb_iter_valid(it) == 1; C.rocksdb_iter_next(it) {
		if max > 0 && i > max {
			break
		}
		var l C.size_t
		// The data returned by rocksdb_iter_{key,value} is not meant to be
		// freed by the client. It is a direct reference to the data managed
		// by the iterator, so it is copied instead of freed.
		data := C.rocksdb_iter_key(it, &l)
		k := C.GoBytes(unsafe.Pointer(data), C.int(l))
		if bytes.Compare(k, end) >= 0 {
			break
		}
		data = C.rocksdb_iter_value(it, &l)
		v := C.GoBytes(unsafe.Pointer(data), C.int(l))
		keyVals = append(keyVals, RawKeyValue{
			Key:   k,
			Value: v,
		})
		i++
	}
	// Check for any errors during iteration.
	var cErr *C.char
	C.rocksdb_iter_get_error(it, &cErr)
	if cErr != nil {
		return nil, charToErr(cErr)
	}
	return keyVals, nil
}
Ejemplo n.º 21
0
// With an unsafe.Pointer to the block of C memory NewIp6Hdr returns a filled in Ip6Hdr struct.
func NewIp6Hdr(p unsafe.Pointer) (*Ip6Hdr, unsafe.Pointer) {
	ip6Hdr := &Ip6Hdr{
		cptr: (*C.struct_ip6_hdr)(p),
		// The fixed header of an IPv6 packet consists of its first 40 octets.
		payload: unsafe.Pointer(uintptr(p) + uintptr(40)),
	}
	ip6Hdr.SrcAddr = net.IP(C.GoBytes(unsafe.Pointer(&ip6Hdr.cptr.ip6_src), 16))
	ip6Hdr.DstAddr = net.IP(C.GoBytes(unsafe.Pointer(&ip6Hdr.cptr.ip6_dst), 16))
	u := (*C.struct_ip6_hdrctl)(unsafe.Pointer(&ip6Hdr.cptr.ip6_ctlun))
	ip6Hdr.NextHeader = uint8(u.ip6_un1_nxt)
	ip6Hdr.PayloadLen = uint16(C.ntohs(u.ip6_un1_plen))
	return ip6Hdr, ip6Hdr.payload
}
Ejemplo n.º 22
0
Archivo: cursor.go Proyecto: raff/bolt
// Seek moves the cursor to a given key and returns it.
// If the key does not exist then the next key is used. If no keys
// follow, an empty value is returned.
func (c *Cursor) Seek(seek []byte) (key, value []byte, flags int) {
	var _flags C.uint32_t
	var _seek, k, v C.bolt_val
	if len(seek) > 0 {
		_seek.size = C.uint32_t(len(seek))
		_seek.data = unsafe.Pointer(&seek[0])
	}
	C.bolt_cursor_seek(c.C, _seek, &k, &v, &_flags)
	if k.data == nil {
		return nil, nil, 0
	}
	return C.GoBytes(k.data, C.int(k.size)), C.GoBytes(v.data, C.int(v.size)), int(_flags)
}
Ejemplo n.º 23
0
func writeToUDP(writer_c unsafe.Pointer, peer_ip unsafe.Pointer, peer_ip_sz C.size_t, peer_port uint16, buffer_c unsafe.Pointer, length_c C.size_t, isServer bool) {
	buf := C.GoBytes(buffer_c, C.int(length_c))

	if isServer {
		peer_addr := &net.UDPAddr{
			IP:   net.IP(C.GoBytes(peer_ip, C.int(peer_ip_sz))),
			Port: int(peer_port),
		}

		((*ServerWriter)(writer_c)).Ch <- UdpData{Buf: buf, Addr: peer_addr}
	} else {
		((*ClientWriter)(writer_c)).Ch <- UdpData{Buf: buf}
	}
}
Ejemplo n.º 24
0
func callbackArgBytes(v *C.sqlite3_value) (reflect.Value, error) {
	switch C.sqlite3_value_type(v) {
	case C.SQLITE_BLOB:
		l := C.sqlite3_value_bytes(v)
		p := C.sqlite3_value_blob(v)
		return reflect.ValueOf(C.GoBytes(p, l)), nil
	case C.SQLITE_TEXT:
		l := C.sqlite3_value_bytes(v)
		c := unsafe.Pointer(C.sqlite3_value_text(v))
		return reflect.ValueOf(C.GoBytes(c, l)), nil
	default:
		return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT")
	}
}
Ejemplo n.º 25
0
func generateSubkey(key []byte) (k1 []byte, k2 []byte) {
	if len(key) != 16 {
		panic("Invalid length.")
	}

	cK1 := (*C.uchar)(C.malloc(16))
	defer C.free(unsafe.Pointer(cK1))

	cK2 := (*C.uchar)(C.malloc(16))
	defer C.free(unsafe.Pointer(cK2))

	C.generate_subkey((*C.uchar)(&key[0]), cK1, cK2)

	return C.GoBytes(unsafe.Pointer(cK1), 16), C.GoBytes(unsafe.Pointer(cK2), 16)
}
Ejemplo n.º 26
0
func NewDnetIOAttr(io *C.struct_dnet_io_attr) DnetIOAttr {
	return DnetIOAttr{
		Parent:      C.GoBytes(unsafe.Pointer(&io.parent[0]), C.int(C.DNET_ID_SIZE)),
		ID:          C.GoBytes(unsafe.Pointer(&io.id[0]), C.int(C.DNET_ID_SIZE)),
		Start:       uint64(C.dnet_io_attr_get_start(io)),
		Num:         uint64(C.dnet_io_attr_get_num(io)),
		Timestamp:   time.Unix(int64(C.dnet_io_attr_get_tsec(io)), int64(C.dnet_io_attr_get_tnsec(io))),
		UserFlags:   uint64(C.dnet_io_attr_get_user_flags(io)),
		TotalSize:   uint64(C.dnet_io_attr_get_total_size(io)),
		Flags:       uint32(C.dnet_io_attr_get_flags(io)),
		Offset:      uint64(C.dnet_io_attr_get_offset(io)),
		Size:        uint64(C.dnet_io_attr_get_size(io)),
		RecordFlags: uint64(C.dnet_io_attr_get_record_flags(io)),
	}
}
Ejemplo n.º 27
0
func (db *DB) get(ro *ReadOptions, key []byte) ([]byte, error) {
	var errStr *C.char
	var vallen C.size_t
	var k *C.char
	if len(key) != 0 {
		k = (*C.char)(unsafe.Pointer(&key[0]))
	}

	var value *C.char

	c := C.leveldb_get_ext(
		db.db, ro.Opt, k, C.size_t(len(key)), &value, &vallen, &errStr)

	if errStr != nil {
		return nil, saveError(errStr)
	}

	if value == nil {
		return nil, nil
	}

	defer C.leveldb_get_free_ext(unsafe.Pointer(c))

	return C.GoBytes(unsafe.Pointer(value), C.int(vallen)), nil
}
Ejemplo n.º 28
0
// function that lists all the xattrs for an object, since xattrs are
// a k-v pair, this function returns a map of k-v pairs on
// success, error code on failure
func (ioctx *IOContext) ListXattrs(oid string) (map[string][]byte, error) {
	c_oid := C.CString(oid)
	defer C.free(unsafe.Pointer(c_oid))

	var it C.rados_xattrs_iter_t

	ret := C.rados_getxattrs(ioctx.ioctx, c_oid, &it)
	if ret < 0 {
		return nil, GetRadosError(ret)
	}
	defer func() { C.rados_getxattrs_end(it) }()
	m := make(map[string][]byte)
	for {
		var c_name, c_val *C.char
		var c_len C.size_t
		defer C.free(unsafe.Pointer(c_name))
		defer C.free(unsafe.Pointer(c_val))

		ret := C.rados_getxattrs_next(it, &c_name, &c_val, &c_len)
		if ret < 0 {
			return nil, GetRadosError(ret)
		}
		// rados api returns a null name,val & 0-length upon
		// end of iteration
		if c_name == nil {
			return m, nil // stop iteration
		}
		m[C.GoString(c_name)] = C.GoBytes(unsafe.Pointer(c_val), (C.int)(c_len))
	}
}
Ejemplo n.º 29
0
func returnArray() []byte {
	var l C.int
	var buf *C.char
	C.return_array(&buf, &l)
	defer C.free(unsafe.Pointer(buf))
	return C.GoBytes(unsafe.Pointer(buf), 12)
}
Ejemplo n.º 30
0
// Encode image.Image with Mapniks image encoder.
func Encode(img image.Image, format string) ([]byte, error) {
	var i *C.mapnik_image_t
	switch img := img.(type) {
	// XXX does mapnik expect NRGBA or RGBA? this might stop working
	//as expected if we start encoding images with full alpha channel
	case *image.NRGBA:
		i = C.mapnik_image_from_raw(
			(*C.uint8_t)(unsafe.Pointer(&img.Pix[0])),
			C.int(img.Bounds().Dx()),
			C.int(img.Bounds().Dy()),
		)
	case *image.RGBA:
		i = C.mapnik_image_from_raw(
			(*C.uint8_t)(unsafe.Pointer(&img.Pix[0])),
			C.int(img.Bounds().Dx()),
			C.int(img.Bounds().Dy()),
		)
	}

	if i == nil {
		return nil, errors.New("unable to create image from raw")
	}
	defer C.mapnik_image_free(i)

	cformat := C.CString(format)
	b := C.mapnik_image_to_blob(i, cformat)
	if b == nil {
		return nil, errors.New("mapnik: " + C.GoString(C.mapnik_image_last_error(i)))
	}
	C.free(unsafe.Pointer(cformat))
	defer C.mapnik_image_blob_free(b)
	return C.GoBytes(unsafe.Pointer(b.ptr), C.int(b.len)), nil
}