Example #1
0
// MakeOIDBytes makes an OID encapsulating a byte slice. Note that it does not
// duplicate the data, but rather it points to it directly.
func (lib *Lib) MakeOIDBytes(data []byte) (*OID, error) {
	oid := lib.NewOID()

	s := C.malloc(C.gss_OID_size) // s for struct
	if s == nil {
		return nil, ErrMallocFailed
	}
	C.memset(s, 0, C.gss_OID_size)

	l := C.size_t(len(data))
	e := C.malloc(l) // c for contents
	if e == nil {
		return nil, ErrMallocFailed
	}
	C.memmove(e, (unsafe.Pointer)(&data[0]), l)

	oid.C_gss_OID = C.gss_OID(s)
	oid.alloc = allocMalloc

	// because of the alignment issues I can't access o.oid's fields from go,
	// so invoking a C function to do the same as:
	// oid.C_gss_OID.length = l
	// oid.C_gss_OID.elements = c
	C.helper_gss_OID_desc_set_elements(oid.C_gss_OID, C.OM_uint32(l), e)

	return oid, nil
}
Example #2
0
func NewTrailDBConstructor(path string, ofields ...string) (*TrailDBConstructor, error) {
	cons := C.tdb_cons_init()
	cpath := C.CString(path)
	defer C.free(unsafe.Pointer(cpath))

	var ofield_p *C.char
	ptrSize := unsafe.Sizeof(ofield_p)

	// Allocate the char** list.
	ptr := C.malloc(C.size_t(len(ofields)) * C.size_t(ptrSize))
	defer C.free(ptr)

	// Assign each byte slice to its appropriate offset.
	for i := 0; i < len(ofields); i++ {
		element := (**C.char)(unsafe.Pointer(uintptr(ptr) + uintptr(i)*ptrSize))
		cofield := C.CString(ofields[i])
		defer C.free(unsafe.Pointer(cofield))
		*element = cofield
	}

	if err := C.tdb_cons_open(cons, cpath, (**C.char)(ptr), C.uint64_t(len(ofields))); err != 0 {
		return nil, errors.New(errToString(err))
	}
	return &TrailDBConstructor{
		cons:         cons,
		path:         path,
		ofields:      ofields,
		valueLengths: make([]C.uint64_t, len(ofields)),
		valuePtr:     C.malloc(C.size_t(len(ofields)) * C.size_t(ptrSize)),
	}, nil
}
Example #3
0
func New(seedHash []byte, block pow.Block) (*Ethash, error) {
	params := new(C.ethash_params)
	n, err := blockNum(block)
	if err != nil {
		return &Ethash{}, err
	}
	C.ethash_params_init(params, C.uint32_t(n))
	log.Println("Params", params)

	var mem unsafe.Pointer
	mem = C.malloc(C.size_t(params.full_size))

	cache := new(C.ethash_cache)
	C.ethash_cache_init(cache, mem)

	log.Println("making full data")
	start := time.Now()
	C.ethash_compute_full_data(mem, params, cache)
	log.Println("took:", time.Since(start))

	var hash *C.uint8_t
	hash = (*C.uint8_t)(C.malloc(32))

	return &Ethash{
		turbo:  false,
		params: params,
		cache:  cache,
		mem:    mem,
		hash:   hash,
	}, nil
}
Example #4
0
// The C side of things will still need to allocate memory, due to the slices.
// Assumes Configuration is valid.
func (config *Configuration) _CGO() *C.CGO_Configuration {
	INFO.Println("Converting Config: ", config)
	size := C.size_t(unsafe.Sizeof(C.CGO_Configuration{}))
	c := (*C.CGO_Configuration)(C.malloc(size))

	// Need to convert each IceServer struct individually.
	total := len(config.IceServers)
	if total > 0 {
		sizeof := unsafe.Sizeof(C.CGO_IceServer{})
		cServers := unsafe.Pointer(C.malloc(C.size_t(sizeof * uintptr(total))))
		ptr := uintptr(cServers)
		for _, server := range config.IceServers {
			*(*C.CGO_IceServer)(unsafe.Pointer(ptr)) = server._CGO()
			ptr += sizeof
		}
		c.iceServers = (*C.CGO_IceServer)(cServers)
	}
	c.numIceServers = C.int(total)

	// c.iceServers = (*C.CGO_IceServer)(unsafe.Pointer(&config.IceServers))
	c.iceTransportPolicy = C.int(config.IceTransportPolicy)
	c.bundlePolicy = C.int(config.BundlePolicy)
	// [ED] c.RtcpMuxPolicy = C.int(config.RtcpMuxPolicy)
	c.peerIdentity = C.CString(config.PeerIdentity)
	// [ED] c.Certificates = config.Certificates
	// [ED] c.IceCandidatePoolSize = C.int(config.IceCandidatePoolSize)
	return c
}
Example #5
0
func LaunchKernel(f Function, gridDimX, gridDimY, gridDimZ int, blockDimX, blockDimY, blockDimZ int, sharedMemBytes int, stream Stream, kernelParams []unsafe.Pointer) {

	// Since Go 1.6, a cgo argument cannot have a Go pointer to Go pointer,
	// so we copy the argument values go C memory first.
	argv := C.malloc(C.size_t(len(kernelParams) * pointerSize))
	argp := C.malloc(C.size_t(len(kernelParams) * pointerSize))
	defer C.free(argv)
	defer C.free(argp)
	for i := range kernelParams {
		*((*unsafe.Pointer)(offset(argp, i))) = offset(argv, i)       // argp[i] = &argv[i]
		*((*uint64)(offset(argv, i))) = *((*uint64)(kernelParams[i])) // argv[i] = *kernelParams[i]
	}

	err := Result(C.cuLaunchKernel(
		C.CUfunction(unsafe.Pointer(uintptr(f))),
		C.uint(gridDimX),
		C.uint(gridDimY),
		C.uint(gridDimZ),
		C.uint(blockDimX),
		C.uint(blockDimY),
		C.uint(blockDimZ),
		C.uint(sharedMemBytes),
		C.CUstream(unsafe.Pointer(uintptr(stream))),
		(*unsafe.Pointer)(argp),
		(*unsafe.Pointer)(unsafe.Pointer(uintptr(0)))))
	if err != SUCCESS {
		panic(err)
	}
}
Example #6
0
//////////////////////////
//      写入接口        //
//////////////////////////
func Store(table *Table,
	primary_key string, // key after encode
	timestamp int64,
	index_list []Index,
	data_list []string) error {
	var c_request C.mdt_store_request_t
	var c_response C.mdt_store_response_t

	// convert request
	c_request.primary_key.data = C.CString(primary_key)
	c_request.primary_key.size = C.size_t(len(primary_key))
	c_request.timestamp = C.int64_t(timestamp)

	c_request.index_list = nil
	c_request.index_list_len = C.size_t(len(index_list))
	c_request.index_list = (*C.mdt_index_t)(C.malloc(32 * c_request.index_list_len))
	c_index_list := (*[1 << 30]C.mdt_index_t)(unsafe.Pointer(c_request.index_list))
	for i := C.size_t(0); i < c_request.index_list_len; i++ {
		c_index_list[i].index_name.data = C.CString(index_list[i].IndexName)
		c_index_list[i].index_name.size = C.size_t(len(index_list[i].IndexName))
		c_index_list[i].index_key.data = C.CString(index_list[i].IndexKey)
		c_index_list[i].index_key.size = C.size_t(len(index_list[i].IndexKey))
	}

	// new vector write interface
	c_request.data_list = nil
	c_request.data_list_len = C.size_t(data_list)
	c_request.data_list = (*C.mdt_slice_t)(C.malloc(16 * c_request.data_list_len))
	c_data_list := (*[1 << 30]C.mdt_slice_t)(unsafe.Pointer(c_request.data_list))
	for i := C.size_t(0); i < c_request.data_list_len; data_i++ {
		c_data_list[i].data = C.CString(data_list[i])
		c_data_list[i].size = C.size_t(len(data_list[i]))
	}
	// old write interface
	//c_request.data.data = C.CString(data)
	//c_request.data.size = C.size_t(len(data))

	// invoke C API
	C.mdt_store(table.rep, &c_request, &c_response, nil, nil)

	// convert result
	err := int(c_response.error)

	// free request memory
	C.free(unsafe.Pointer(c_request.primary_key.data))

	for i := C.size_t(0); i < c_request.index_list_len; i++ {
		C.free(unsafe.Pointer(c_index_list[i].index_name.data))
		C.free(unsafe.Pointer(c_index_list[i].index_key.data))
	}
	C.free(unsafe.Pointer(c_request.index_list))

	for i := C.size_t(0); i < c_request.data_list_len; i++ {
		C.free(unsafe.Pointer(c_data_list[i].data))
	}
	C.free(unsafe.Pointer(c_request.data_list))
	//C.free(unsafe.Pointer(c_request.data.data))

	return GetError(err)
}
Example #7
0
func generateCmac(key []byte, msg []byte) []byte {
	if len(key) != 16 {
		panic("Invalid length.")
	}

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

	var msgStart *C.uchar
	if len(msg) > 0 {
		msgStart = (*C.uchar)(&msg[0])
	} else {
		// Avoid indexing into empty slice/C array.
		msgStart = (*C.uchar)(C.malloc(1))
		defer C.free(unsafe.Pointer(msgStart))
	}

	C.AES_CMAC(
		(*C.uchar)(&key[0]),
		msgStart,
		C.int(len(msg)),
		cMac)

	return C.GoBytes(unsafe.Pointer(cMac), 16)
}
Example #8
0
// Append the map `pairs` to the omap `oid`
func (ioctx *IOContext) SetOmap(oid string, pairs map[string][]byte) error {
	c_oid := C.CString(oid)
	defer C.free(unsafe.Pointer(c_oid))

	var s C.size_t
	var c *C.char
	ptrSize := unsafe.Sizeof(c)

	c_keys := C.malloc(C.size_t(len(pairs)) * C.size_t(ptrSize))
	c_values := C.malloc(C.size_t(len(pairs)) * C.size_t(ptrSize))
	c_lengths := C.malloc(C.size_t(len(pairs)) * C.size_t(unsafe.Sizeof(s)))

	defer C.free(unsafe.Pointer(c_keys))
	defer C.free(unsafe.Pointer(c_values))
	defer C.free(unsafe.Pointer(c_lengths))

	i := 0
	for key, value := range pairs {
		// key
		c_key_ptr := (**C.char)(unsafe.Pointer(uintptr(c_keys) + uintptr(i)*ptrSize))
		*c_key_ptr = C.CString(key)
		defer C.free(unsafe.Pointer(*c_key_ptr))

		// value and its length
		c_value_ptr := (**C.char)(unsafe.Pointer(uintptr(c_values) + uintptr(i)*ptrSize))

		var c_length C.size_t
		if len(value) > 0 {
			*c_value_ptr = (*C.char)(unsafe.Pointer(&value[0]))
			c_length = C.size_t(len(value))
		} else {
			*c_value_ptr = nil
			c_length = C.size_t(0)
		}

		c_length_ptr := (*C.size_t)(unsafe.Pointer(uintptr(c_lengths) + uintptr(i)*ptrSize))
		*c_length_ptr = c_length

		i++
	}

	op := C.rados_create_write_op()
	C.rados_write_op_omap_set(
		op,
		(**C.char)(c_keys),
		(**C.char)(c_values),
		(*C.size_t)(c_lengths),
		C.size_t(len(pairs)))

	ret := C.rados_write_op_operate(op, ioctx.ioctx, c_oid, nil, 0)
	C.rados_release_write_op(op)

	if ret == 0 {
		return nil
	} else {
		return RadosError(int(ret))
	}
}
Example #9
0
func GetNthAircraftModel(index int) (fileName, path string) {
	nameBuf := (*C.char)(C.malloc(256))
	defer C.free(unsafe.Pointer(nameBuf))
	pathBuf := (*C.char)(C.malloc(512))
	defer C.free(unsafe.Pointer(pathBuf))
	C.XPLMGetNthAircraftModel((C.int)(index), nameBuf, pathBuf)
	fileName = C.GoString(nameBuf)
	path = C.GoString(pathBuf)
	return
}
Example #10
0
func Spawn(loop *Loop, options ProcessOptions) (err error) {
	if loop == nil {
		loop = DefaultLoop()
	}

	var opt C.uv_process_options_t
	defer func() {
		/*
			C.free(unsafe.Pointer(opt.file))
			if len(options.Args) > 0 {
				for n := 0; n < len(options.Args); n++ {
					C.free(unsafe.Pointer(((*[1<<24]*C.char)(unsafe.Pointer(&opt.args)))[n]))
				}
				C.free(unsafe.Pointer(opt.args))
			}
			if len(options.Env) > 0 {
				for n := 0; n < len(options.Env); n++ {
					C.free(unsafe.Pointer(((*[1<<24]*C.char)(unsafe.Pointer(&opt.env)))[n]))
				}
				C.free(unsafe.Pointer(opt.env))
			}
			C.free(unsafe.Pointer(opt.cwd))
		*/
	}()
	if len(options.File) > 0 {
		opt.file = C.CString(options.File)
	}
	if len(options.Args) > 0 {
		opt.args = (**C.char)(C.malloc(C.size_t(4 * (len(options.Args) + 1))))
		for n := 0; n < len(options.Args); n++ {
			((*[1 << 24]*C.char)(unsafe.Pointer(&opt.args)))[n] = C.CString(options.Args[n])
		}
		((*[1 << 24]*C.char)(unsafe.Pointer(&opt.args)))[len(options.Args)] = nil
	}
	if len(options.Env) > 0 {
		opt.env = (**C.char)(C.malloc(C.size_t(4 * (len(options.Env) + 1))))
		for n := 0; n < len(options.Args); n++ {
			((*[1 << 24]*C.char)(unsafe.Pointer(&opt.env)))[n] = C.CString(options.Args[n])
		}
		((*[1 << 24]*C.char)(unsafe.Pointer(&opt.env)))[len(options.Args)] = nil
	}
	if len(options.Cwd) > 0 {
		opt.cwd = C.CString(options.Cwd)
	}
	// TODO: uv_stdio_container_t

	var p C.uv_process_t
	p.data = unsafe.Pointer(&callback_info{exit_cb: options.Exit_cb})
	r := uv_spawn(loop.l, &p, opt)
	if r != 0 {
		return loop.LastError().Error()
	}
	return nil
}
Example #11
0
func test6390(t *testing.T) {
	p1 := C.malloc(1024)
	if p1 == nil {
		t.Fatalf("C.malloc(1024) returned nil")
	}
	p2 := C.malloc(0)
	if p2 == nil {
		t.Fatalf("C.malloc(0) returned nil")
	}
	C.free(p1)
	C.free(p2)
}
Example #12
0
// List clients that have locked the named object lock and information about the lock.
// The number of bytes required in each buffer is put in the corresponding size out parameter.
// If any of the provided buffers are too short, -ERANGE is returned after these sizes are filled in.
func (ioctx *IOContext) ListLockers(oid, name string) (*LockInfo, error) {
	c_oid := C.CString(oid)
	c_name := C.CString(name)

	c_tag := (*C.char)(C.malloc(C.size_t(1024)))
	c_clients := (*C.char)(C.malloc(C.size_t(1024)))
	c_cookies := (*C.char)(C.malloc(C.size_t(1024)))
	c_addrs := (*C.char)(C.malloc(C.size_t(1024)))

	var c_exclusive C.int
	c_tag_len := C.size_t(1024)
	c_clients_len := C.size_t(1024)
	c_cookies_len := C.size_t(1024)
	c_addrs_len := C.size_t(1024)

	defer C.free(unsafe.Pointer(c_oid))
	defer C.free(unsafe.Pointer(c_name))
	defer C.free(unsafe.Pointer(c_tag))
	defer C.free(unsafe.Pointer(c_clients))
	defer C.free(unsafe.Pointer(c_cookies))
	defer C.free(unsafe.Pointer(c_addrs))

	ret := C.rados_list_lockers(
		ioctx.ioctx,
		c_oid,
		c_name,
		&c_exclusive,
		c_tag,
		&c_tag_len,
		c_clients,
		&c_clients_len,
		c_cookies,
		&c_cookies_len,
		c_addrs,
		&c_addrs_len)

	splitCString := func(items *C.char, itemsLen C.size_t) []string {
		currLen := 0
		clients := []string{}
		for currLen < int(itemsLen) {
			client := C.GoString(C.nextChunk(&items))
			clients = append(clients, client)
			currLen += len(client) + 1
		}
		return clients
	}

	if ret < 0 {
		return nil, RadosError(int(ret))
	} else {
		return &LockInfo{int(ret), c_exclusive == 1, C.GoString(c_tag), splitCString(c_clients, c_clients_len), splitCString(c_cookies, c_cookies_len), splitCString(c_addrs, c_addrs_len)}, nil
	}
}
Example #13
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)
}
Example #14
0
func doFinish(call rpc.ClientCall, numResults int) (C.SwiftByteArrayArray, error) {
	// Have all the results be decoded into *vdl.Value.
	resultPtrs := make([]interface{}, numResults)
	for i := 0; i < numResults; i++ {
		value := new(vdl.Value)
		resultPtrs[i] = &value
	}
	if err := call.Finish(resultPtrs...); err != nil {
		// Invocation error.
		return EmptySwiftByteArrayArray(), err
	}

	// VOM-encode the results. Note in the future we'll want a pathway where we can get the original VOM results
	// from finish so we don't end up wasting CPU & memory here.

	// Prepare the byte array array that can be accessed from Swift via C.malloc
	vomResultsMemory := C.malloc(C.size_t(numResults * int(C.sizeofSwiftByteArray)))
	// Make that malloc'd memory available as a slice to Go.
	vomResultsPtrsHdr := reflect.SliceHeader{
		Data: uintptr(vomResultsMemory),
		Len:  numResults,
		Cap:  numResults,
	}
	vomResults := *(*[]C.SwiftByteArray)(unsafe.Pointer(&vomResultsPtrsHdr))
	// Create the C Struct to return that encapsulates our byte array array
	var cVomResults C.SwiftByteArrayArray
	cVomResults.length = C._GoUint64(numResults)
	cVomResults.data = (*C.SwiftByteArray)(vomResultsMemory)

	// For each result, VOM encode into a byte array that we stick into the returned struct
	for i, resultPtr := range resultPtrs {
		// Remove the pointer from the result.  Simply *resultPtr doesn't work
		// as resultPtr is of type interface{}.
		result := interface{}(sutil.DerefOrDie(resultPtr))
		var vomResult []byte
		var err error
		if vomResult, err = vom.Encode(result); err != nil {
			return EmptySwiftByteArrayArray(), err
		}
		cVomResultCopy := C.malloc(C.size_t(len(vomResult)))
		C.memcpy(cVomResultCopy, unsafe.Pointer(&vomResult[0]), C.size_t(len(vomResult)))
		var cVomResult C.SwiftByteArray
		cVomResult.length = C._GoUint64(len(vomResult))
		cVomResult.data = cVomResultCopy
		vomResults[i] = cVomResult
	}
	return cVomResults, nil
}
Example #15
0
func GetShaderInfoLog(s Shader) string {
	infoLen := GetShaderi(s, INFO_LOG_LENGTH)
	buf := C.malloc(C.size_t(infoLen))
	defer C.free(buf)
	C.glGetShaderInfoLog(s.c(), C.GLsizei(infoLen), nil, (*C.GLchar)(buf))
	return C.GoString((*C.char)(buf))
}
Example #16
0
// Full customization of the call. Arguments essentially map to UI_UTIL_read_pw_string
func GetPassWithOptions(prompt string, confirm, max int) (pw string, e error) {

	pw = ""
	e = nil

	if max <= 0 {
		e = errors.New("Invalid argument: maximum password length")
		return pw, e
	}

	if len(prompt) <= 0 {
		e = errors.New("Invalid argument: prompt")
		return pw, e
	}

	sz := C.int(max)
	buf := C.malloc(C.size_t(sz))
	bptr := (*C.char)(buf)
	p := C.CString(prompt)

	rc, err := C.UI_UTIL_read_pw_string(bptr, sz, p, C.int(confirm))
	if rc != 0 {
		e = err
	} else {
		pw = C.GoString(bptr)
	}

	C.free(buf)
	return pw, e
}
Example #17
0
func GetProgramInfoLog(p Program) string {
	infoLen := GetProgrami(p, INFO_LOG_LENGTH)
	buf := C.malloc(C.size_t(infoLen))
	C.free(buf)
	C.glGetProgramInfoLog(p.c(), C.GLsizei(infoLen), nil, (*C.GLchar)(buf))
	return C.GoString((*C.char)(buf))
}
Example #18
0
func (d *VirDomain) GetVcpusCpuMap(maxInfo int, maxCPUs uint32) ([]VirVcpuInfo, error) {
	ptr := make([]C.virVcpuInfo, maxInfo)

	mapLen := virCpuMapLen(maxCPUs)                    // Length of CPUs bitmask in bytes
	bufSize := int(mapLen) * int(maxInfo)              // Length of the array of 'maxinfo' bitmasks
	cpuMaps := (*C.uchar)(C.malloc(C.size_t(bufSize))) // Array itself
	defer C.free(unsafe.Pointer(cpuMaps))

	result := C.virDomainGetVcpus(
		d.ptr, (C.virVcpuInfoPtr)(unsafe.Pointer(&ptr[0])),
		C.int(maxInfo), cpuMaps, mapLen)

	if result == -1 {
		return nil, GetLastError()
	}

	// Convert to golang []byte for easier handling
	bytesCpuMaps := C.GoBytes(unsafe.Pointer(cpuMaps), C.int(bufSize))

	out := make([]VirVcpuInfo, 0)
	for i := 0; i < int(result); i++ {
		out = append(out, VirVcpuInfo{
			Number:  uint32(ptr[i].number),
			State:   int32(ptr[i].state),
			CpuTime: uint64(ptr[i].cpuTime),
			Cpu:     int32(ptr[i].cpu),
			CpuMap:  extractCpuMask(bytesCpuMaps, i, int(mapLen)),
		})
	}

	return out, nil
}
Example #19
0
File: mdt.go Project: bdtbd/mdt
func ConvertBatchWriteRequest(wb *BatchWriteContext, c_wb *C.mdt_batch_write_context_t) error {
	var req C.mdt_store_request_t
	c_wb.nr_batch = C.uint64_t(wb.NumberBatch)
	c_wb.error = 0
	c_wb.batch_req = (*C.mdt_store_request_t)(C.malloc(C.size_t(unsafe.Sizeof(req)) * C.size_t(c_wb.nr_batch)))
	c_batch_req := (*[1 << 30]C.mdt_store_request_t)(unsafe.Pointer(c_wb.batch_req))
	for i := C.size_t(0); i < C.size_t(c_wb.nr_batch); i++ {
		ConvertWriteRequest(&(wb.Context[i]), &(c_batch_req[i]))
	}

	// alloc response memory
	var resp C.mdt_store_response_t
	c_wb.resp = (*C.mdt_store_response_t)(C.malloc(C.size_t(unsafe.Sizeof(resp)) * C.size_t(c_wb.nr_batch)))

	return nil
}
Example #20
0
// Remove the specified `keys` from the omap `oid`
func (ioctx *IOContext) RmOmapKeys(oid string, keys []string) error {
	c_oid := C.CString(oid)
	defer C.free(unsafe.Pointer(c_oid))

	var c *C.char
	ptrSize := unsafe.Sizeof(c)

	c_keys := C.malloc(C.size_t(len(keys)) * C.size_t(ptrSize))
	defer C.free(unsafe.Pointer(c_keys))

	i := 0
	for _, key := range keys {
		c_key_ptr := (**C.char)(unsafe.Pointer(uintptr(c_keys) + uintptr(i)*ptrSize))
		*c_key_ptr = C.CString(key)
		defer C.free(unsafe.Pointer(*c_key_ptr))
		i++
	}

	op := C.rados_create_write_op()
	C.rados_write_op_omap_rm_keys(
		op,
		(**C.char)(c_keys),
		C.size_t(len(keys)))

	ret := C.rados_write_op_operate(op, ioctx.ioctx, c_oid, nil, 0)
	C.rados_release_write_op(op)

	return GetRadosError(ret)
}
Example #21
0
// Because Go is like... naaaaa, no groups aren't a thing!
// Based on Go's src/os/user/lookup_unix.go
func currentUserAndGroup() (*userAndGroup, error) {
	u, err := user.Current()
	if err != nil {
		return nil, err
	}
	gid, err := strconv.Atoi(u.Gid)
	if err != nil {
		return nil, err
	}

	var grp C.struct_group
	var result *C.struct_group
	buflen := C.sysconf(C._SC_GETPW_R_SIZE_MAX)
	if buflen <= 0 || buflen > 1<<20 {
		return nil, fmt.Errorf("unreasonable _SC_GETGR_R_SIZE_MAX of %d", buflen)
	}
	buf := C.malloc(C.size_t(buflen))
	defer C.free(buf)

	r := C.mygetgrgid_r(C.gid_t(gid), &grp,
		(*C.char)(buf),
		C.size_t(buflen),
		&result)
	if r != 0 {
		return nil, fmt.Errorf("lookup gid %d: %s", gid, syscall.Errno(r))
	}
	if result == nil {
		return nil, fmt.Errorf("lookup gid %d failed", gid)
	}

	return &userAndGroup{
		User:      u,
		Groupname: C.GoString(grp.gr_name),
	}, nil
}
Example #22
0
// GroupId is an adaption from https://codereview.appspot.com/4589049.
func GroupId(name string) (int, error) {
	var grp C.struct_group
	var result *C.struct_group

	bufSize := C.size_t(C.sysconf(C._SC_GETGR_R_SIZE_MAX))
	buf := C.malloc(bufSize)
	if buf == nil {
		return -1, fmt.Errorf(gettext.Gettext("allocation failed"))
	}
	defer C.free(buf)

	// mygetgrgid_r is a wrapper around getgrgid_r to
	// to avoid using gid_t because C.gid_t(gid) for
	// unknown reasons doesn't work on linux.
	rv := C.getgrnam_r(C.CString(name),
		&grp,
		(*C.char)(buf),
		bufSize,
		&result)

	if rv != 0 {
		return -1, fmt.Errorf(gettext.Gettext("failed group lookup: %s"), syscall.Errno(rv))
	}

	if result == nil {
		return -1, fmt.Errorf(gettext.Gettext("unknown group %s"), name)
	}

	return int(C.int(result.gr_gid)), nil
}
Example #23
0
func SetMLReply(ctx uintptr, rcode, xcode string, message ...string) int {
	/*  Allows up to 32 lines of message
	 */

	crcode := C.CString(rcode)
	defer C.free(unsafe.Pointer(crcode))
	cxcode := C.CString(xcode)
	defer C.free(unsafe.Pointer(cxcode))

	// Build message C array
	// Get size of a C pointer on this system
	ptrSize := unsafe.Sizeof(crcode)

	// Allocate the char** array
	argv := C.malloc(C.size_t(len(message)) * C.size_t(ptrSize))
	defer C.free(argv)
	// Assign each line to its address offset
	for i := 0; i < len(message); i++ {
		linePtr := (**C.char)(unsafe.Pointer(uintptr(argv) + uintptr(i)*ptrSize))
		line := C.CString(message[i])
		defer C.free(unsafe.Pointer(line))
		*linePtr = line
	}

	// Call our C wrapper for setmlreply
	// The wrapper is needed as cgo doesn't support variadic C function calls
	return int(C.wrap_setmlreply(int2ctx(ctx), crcode, cxcode, C.int(len(message)), (**C.char)(argv)))
}
Example #24
0
// Import imports the nodes and edges from a serialized representation of
// another Graph into g.
//
// Names of imported nodes will be prefixed with prefix.
func (g *Graph) Import(def []byte, prefix string) error {
	cprefix := C.CString(prefix)
	defer C.free(unsafe.Pointer(cprefix))

	opts := C.TF_NewImportGraphDefOptions()
	defer C.TF_DeleteImportGraphDefOptions(opts)
	C.TF_ImportGraphDefOptionsSetPrefix(opts, cprefix)

	buf := C.TF_NewBuffer()
	defer C.TF_DeleteBuffer(buf)
	// Would have preferred to use C.CBytes, but that does not play well
	// with "go vet" till https://github.com/golang/go/issues/17201 is
	// resolved.
	buf.length = C.size_t(len(def))
	buf.data = C.malloc(buf.length)
	if buf.data == nil {
		return fmt.Errorf("unable to allocate memory")
	}
	defer C.free(buf.data)
	C.memcpy(buf.data, unsafe.Pointer(&def[0]), buf.length)

	status := newStatus()
	C.TF_GraphImportGraphDef(g.c, buf, opts, status.c)
	if err := status.Err(); err != nil {
		return err
	}
	return nil
}
Example #25
0
func main() {
	p := C.malloc(C.size_t(1))
	if p == nil {
		C.perror(C.CString("malloc failure"))
	}
	defer C.free(p)
	C.strcpy((*C.char)(p), (*C.char)(C.CString("123")))
	C.strcat((*C.char)(p), C.CString("233"))
	fmt.Printf(C.GoString((*C.char)(p)))

	ts := C.malloc(C.size_t(unsafe.Sizeof(C.struct_Test{})))
	if ts == nil {
		C.perror(C.CString("malloc struct"))
	}
	defer C.free(ts)
}
Example #26
0
File: lookup.go Project: CSUA/pushy
// TODO: properly attribute http://golang.org/src/pkg/os/user/lookup_unix.go (BSD-style: http://golang.org/LICENSE)
func GetGidByName(name string) (gid int, err error) {
	var group C.struct_group
	var result *C.struct_group

	var bufSize C.long
	bufSize = C.sysconf(C._SC_GETGR_R_SIZE_MAX)
	if bufSize <= 0 || bufSize > 1<<20 {
		log.Fatalf("ERROR: unreasonable _SC_GETGR_R_SIZE_MAX of %d", bufSize)
	}
	buf := C.malloc(C.size_t(bufSize))
	defer C.free(buf)

	var returnValue C.int
	nameC := C.CString(config.Group)
	defer C.free(unsafe.Pointer(nameC))
	returnValue = C.getgrnam_r(nameC,
		&group,
		(*C.char)(buf),
		C.size_t(bufSize),
		&result)
	if returnValue != 0 {
		return -1, fmt.Errorf("ERROR: error looking up group", name, syscall.Errno(returnValue))
	}
	if result == nil {
		return -1, UnknownLookupError(name)
	}
	gid = int(result.gr_gid)
	return
}
Example #27
0
func getGroupName(fi os.FileInfo) (string, error) {
	var rv C.int
	var grp C.struct_group
	var grpres *C.struct_group
	var bufSize C.long
	var result string

	bufSize = 1024
	buf := C.malloc(C.size_t(bufSize))
	defer C.free(buf)

	gid := fi.Sys().(*syscall.Stat_t).Gid

	rv = C.mygetgrgid_r(C.int(gid), &grp, (*C.char)(buf), C.size_t(bufSize), &grpres)
	if rv != 0 {
		return "", errors.New("Could not read groupname")
	}

	if grpres != nil {
		result = C.GoString(grp.gr_name)
	} else {
		return "", errors.New("Could not convert groupname")
	}
	return result, nil
}
Example #28
0
func getUserName(fi os.FileInfo) (string, error) {
	var rv C.int
	var pwd C.struct_passwd
	var pwdres *C.struct_passwd
	var bufSize C.long
	var result string

	bufSize = 1024
	buf := C.malloc(C.size_t(bufSize))
	defer C.free(buf)

	uid := fi.Sys().(*syscall.Stat_t).Uid

	rv = C.mygetpwuid_r(C.int(uid), &pwd, (*C.char)(buf), C.size_t(bufSize), &pwdres)
	if rv != 0 {
		return "", errors.New("Could not read username")
	}

	if pwdres != nil {
		result = C.GoString(pwd.pw_name)
	} else {
		return "", errors.New("Could not convert username")
	}

	return result, nil
}
Example #29
0
func makeSourceManager(src io.Reader, dinfo *C.struct_jpeg_decompress_struct) (mgr *sourceManager) {
	mgr = new(sourceManager)
	mgr.src = src
	mgr.pub = C.malloc_jpeg_source_mgr()
	if mgr.pub == nil {
		panic("Failed to allocate C.struct_jpeg_source_mgr")
	}
	mgr.buffer = C.malloc(readBufferSize)
	if mgr.buffer == nil {
		panic("Failed to allocate buffer")
	}
	mgr.pub.init_source = (*[0]byte)(C.sourceInit)
	mgr.pub.fill_input_buffer = (*[0]byte)(C.sourceFill)
	mgr.pub.skip_input_data = (*[0]byte)(C.sourceSkip)
	mgr.pub.resync_to_restart = (*[0]byte)(C._get_jpeg_resync_to_restart())
	mgr.pub.term_source = (*[0]byte)(C.sourceTerm)
	mgr.pub.bytes_in_buffer = 0
	mgr.pub.next_input_byte = nil
	dinfo.src = mgr.pub

	sourceManagerMapMutex.Lock()
	defer sourceManagerMapMutex.Unlock()
	sourceManagerMap[uintptr(unsafe.Pointer(mgr.pub))] = mgr

	return
}
Example #30
0
func s2v(key []byte, strings [][]byte) []byte {
	if len(key) == 0 {
		panic("Key must be non-empty.")
	}

	// RFC 5297 defines S2V to handle an empty array, but never actually uses it
	// that way for encryption or decryption. Additionally, the s2v_* reference
	// functions don't handle that case. So don't handle it here.
	if len(strings) == 0 {
		panic("strings must be non-empty.")
	}

	// siv_init requires a full SIV key, i.e. twice the length of the key used by
	// S2V. It uses the first half for the S2V key.
	tmpKey := make([]byte, 2*len(key))
	copy(tmpKey, key)
	key = tmpKey

	// Initialize the context struct.
	var ctx C.siv_ctx
	callResult := C.siv_init(&ctx, (*C.uchar)(&key[0]), C.int(8*len(key)))
	if callResult < 0 {
		panic("Error from siv_init.")
	}

	// Call s2v_update the requisite number of times.
	for i := 0; i < len(strings)-1; i++ {
		data := strings[i]
		dataLen := len(data)

		// Avoid indexing into an empty slice.
		if dataLen == 0 {
			data = make([]byte, 1)
		}

		C.s2v_update(&ctx, (*C.uchar)(&data[0]), C.int(dataLen))
	}

	// Now finalize with the last string. Avoid indexing into an empty slice.
	lastString := strings[len(strings)-1]
	lastStringLen := len(lastString)
	if lastStringLen == 0 {
		lastString = make([]byte, 1)
	}

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

	callResult = C.s2v_final(
		&ctx,
		(*C.uchar)(&lastString[0]),
		C.int(lastStringLen),
		cDigest)

	if callResult < 0 {
		panic("Error from s2v_final.")
	}

	return C.GoBytes(unsafe.Pointer(cDigest), 16)
}