Example #1
2
//export callback_friend_request
func callback_friend_request(
	c_tox *C.Tox,
	c_public_key *C.uint8_t,
	c_message *C.uint8_t,
	c_length C.size_t,
	c_user_data unsafe.Pointer,
) {
	// Initialize variables.
	tox := (*Tox)(c_user_data)
	var publicKey ToxPublicKey
	message := make([]byte, c_length)
	// Copy the public key.
	C.memcpy(
		unsafe.Pointer(&publicKey[0]),
		unsafe.Pointer(c_public_key),
		ToxPublicKeySize,
	)
	// Copy the friend request message.
	if c_length > 0 {
		C.memcpy(
			unsafe.Pointer(&message[0]),
			unsafe.Pointer(c_message),
			c_length,
		)
	}
	// Register the callback.
	tox.onFriendRequest(tox, publicKey, message)
}
Example #2
0
File: magick.go Project: mat/magick
// GetProperty() retreives the given attribute or freeform property
// string on the underlying Image
func (im *MagickImage) GetProperty(prop string) (value string) {
	c_prop := C.CString(prop)
	defer C.free(unsafe.Pointer(c_prop))
	c_value := C.GetImageProperty(im.Image, c_prop)
	defer C.free(unsafe.Pointer(c_value))
	return C.GoString(c_value)
}
Example #3
0
// Returns the list of available screen dimensions for the given format.
//
// NOTE: The result of this function uses a different encoding than the underlying C function.
// It returns an empty array if no modes are available,
// and nil if any dimension is okay for the given format.
func ListModes(format *PixelFormat, flags uint32) []Rect {
	modes := C.SDL_ListModes((*C.SDL_PixelFormat)(cast(format)), C.Uint32(flags))

	// No modes available
	if modes == nil {
		return make([]Rect, 0)
	}

	// (modes == -1) --> Any dimension is ok
	if uintptr(unsafe.Pointer(modes))+1 == uintptr(0) {
		return nil
	}

	count := 0
	ptr := *modes //first element in the list
	for ptr != nil {
		count++
		ptr = *(**C.SDL_Rect)(unsafe.Pointer(uintptr(unsafe.Pointer(modes)) + uintptr(count*unsafe.Sizeof(ptr))))
	}

	ret := make([]Rect, count)
	for i := 0; i < count; i++ {
		ptr := (**C.SDL_Rect)(unsafe.Pointer(uintptr(unsafe.Pointer(modes)) + uintptr(i*unsafe.Sizeof(*modes))))
		var r *C.SDL_Rect = *ptr
		ret[i].X = int16(r.x)
		ret[i].Y = int16(r.y)
		ret[i].W = uint16(r.w)
		ret[i].H = uint16(r.h)
	}

	return ret
}
Example #4
0
func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) {
	var _p0 *byte
	_p0, err = BytePtrFromString(source)
	if err != nil {
		return
	}
	var _p1 *byte
	_p1, err = BytePtrFromString(target)
	if err != nil {
		return
	}
	var _p2 *byte
	_p2, err = BytePtrFromString(fstype)
	if err != nil {
		return
	}
	_, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0)
	use(unsafe.Pointer(_p0))
	use(unsafe.Pointer(_p1))
	use(unsafe.Pointer(_p2))
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}
Example #5
0
func getBuffer(s *reflect.SliceHeader, p *C.PaStreamParameters) (unsafe.Pointer, int, error) {
	if p.sampleFormat&C.paNonInterleaved == 0 {
		n := int(p.channelCount)
		if s.Len%n != 0 {
			return nil, 0, fmt.Errorf("length of interleaved buffer not divisible by number of channels")
		}
		return unsafe.Pointer(s.Data), s.Len / n, nil
	} else {
		if s.Len != int(p.channelCount) {
			return nil, 0, fmt.Errorf("buffer has wrong number of channels")
		}
		buf := make([]uintptr, s.Len)
		frames := -1
		sp := s.Data
		for i := range buf {
			ch := (*reflect.SliceHeader)(unsafe.Pointer(sp))
			if frames == -1 {
				frames = ch.Len
			} else if ch.Len != frames {
				return nil, 0, fmt.Errorf("channels have different lengths")
			}
			buf[i] = ch.Data
			sp += unsafe.Sizeof(reflect.SliceHeader{})
		}
		return unsafe.Pointer(&buf[0]), frames, nil
	}
}
Example #6
0
func (ic *Iconv) convert(input []byte, out io.Writer, outBuf []byte) (bytesConverted int, err error) {
	inputLen := len(input)
	if inputLen == 0 {
		return
	}

	outputLen := len(outBuf)
	if outputLen == 0 {
		outputLen = inputLen
		outBuf = make([]byte, outputLen)
	}

	outputPtr := &outBuf[0]
	outputPtrPtr := (**C.char)(unsafe.Pointer(&outputPtr))
	outputBytesLeft := C.size_t(outputLen)

	inputPtr := &input[0]
	inputPtrPtr := (**C.char)(unsafe.Pointer(&inputPtr))
	inputBytesLeft := C.size_t(inputLen)

	_, err = C.iconv(ic.pIconv, inputPtrPtr, &inputBytesLeft, outputPtrPtr, &outputBytesLeft)
	bytesConverted = inputLen - int(inputBytesLeft)
	if int(outputBytesLeft) < outputLen {
		out.Write(outBuf[:outputLen-int(outputBytesLeft)])
	}
	return
}
Example #7
0
func (c *driverConn) Prepare(query string) (driver.Stmt, error) {
	// Generate unique statement name.
	stmtname := strconv.Itoa(c.stmtNum)
	cstmtname := C.CString(stmtname)
	c.stmtNum++
	defer C.free(unsafe.Pointer(cstmtname))
	stmtstr := C.CString(query)
	defer C.free(unsafe.Pointer(stmtstr))
	res := C.PQprepare(c.db, cstmtname, stmtstr, 0, nil)
	err := resultError(res)
	if err != nil {
		C.PQclear(res)
		return nil, err
	}
	stmtinfo := C.PQdescribePrepared(c.db, cstmtname)
	err = resultError(stmtinfo)
	if err != nil {
		C.PQclear(stmtinfo)
		return nil, err
	}
	defer C.PQclear(stmtinfo)
	nparams := int(C.PQnparams(stmtinfo))
	statement := &driverStmt{stmtname, c.db, res, nparams}
	runtime.SetFinalizer(statement, (*driverStmt).Close)
	return statement, nil
}
Example #8
0
func (bnd *bndTimePtr) bind(value *time.Time, position int, stmt *Stmt) error {
	bnd.stmt = stmt
	bnd.value = value
	r := C.OCIDescriptorAlloc(
		unsafe.Pointer(bnd.stmt.ses.srv.env.ocienv),         //CONST dvoid   *parenth,
		(*unsafe.Pointer)(unsafe.Pointer(&bnd.ociDateTime)), //dvoid         **descpp,
		C.OCI_DTYPE_TIMESTAMP_TZ,                            //ub4           type,
		0,   //size_t        xtramem_sz,
		nil) //dvoid         **usrmempp);
	if r == C.OCI_ERROR {
		return bnd.stmt.ses.srv.env.ociError()
	} else if r == C.OCI_INVALID_HANDLE {
		return errNew("unable to allocate oci timestamp handle during bind")
	}
	r = C.OCIBINDBYPOS(
		bnd.stmt.ocistmt,                              //OCIStmt      *stmtp,
		(**C.OCIBind)(&bnd.ocibnd),                    //OCIBind      **bindpp,
		bnd.stmt.ses.srv.env.ocierr,                   //OCIError     *errhp,
		C.ub4(position),                               //ub4          position,
		unsafe.Pointer(&bnd.ociDateTime),              //void         *valuep,
		C.LENGTH_TYPE(unsafe.Sizeof(bnd.ociDateTime)), //sb8          value_sz,
		C.SQLT_TIMESTAMP_TZ,                           //ub2          dty,
		unsafe.Pointer(&bnd.isNull),                   //void         *indp,
		nil,           //ub2          *alenp,
		nil,           //ub2          *rcodep,
		0,             //ub4          maxarr_len,
		nil,           //ub4          *curelep,
		C.OCI_DEFAULT) //ub4          mode );
	if r == C.OCI_ERROR {
		return bnd.stmt.ses.srv.env.ociError()
	}
	return nil
}
Example #9
0
// Sets the debugging hook function.
//
// Argument fn is the hook function. mask specifies on which events the hook
// will be called: it is formed by a bitwise OR of the constants Maskcall,
// Maskret, Maskline, and Maskcount. The count argument is only meaningful
// when the mask includes Maskcount. The hook is called for each event type
// present in mask.
//
// A hook is disabled by setting mask to 0.
func (s *State) Sethook(fn Hook, mask, count int) error {
	s.Getglobal(namehooks)
	if mask&Maskcall == Maskcall {
		s.Pushstring(namecall)
		s.Pushlightuserdata(unsafe.Pointer(&fn))
		s.Settable(-3)
	}
	if mask&Maskret == Maskret {
		s.Pushstring(nameret)
		s.Pushlightuserdata(unsafe.Pointer(&fn))
		s.Settable(-3)
	}
	if mask&Maskline == Maskline {
		s.Pushstring(nameline)
		s.Pushlightuserdata(unsafe.Pointer(&fn))
		s.Settable(-3)
	}
	if mask&Maskcount == Maskcount {
		s.Pushstring(namecount)
		s.Pushlightuserdata(unsafe.Pointer(&fn))
		s.Settable(-3)
	}
	s.Pop(1) // pop hook table
	C.sethook(s.l, C.int(mask), C.int(count))
	return nil
}
Example #10
0
func init() {
	// CUDA driver kernel call wants pointers to arguments, set them up once.
	zeromask_args.argptr[0] = unsafe.Pointer(&zeromask_args.arg_dst)
	zeromask_args.argptr[1] = unsafe.Pointer(&zeromask_args.arg_maskLUT)
	zeromask_args.argptr[2] = unsafe.Pointer(&zeromask_args.arg_regions)
	zeromask_args.argptr[3] = unsafe.Pointer(&zeromask_args.arg_N)
}
Example #11
0
// CmdGetMapped returns the interface settings in a map
func (e *Ethtool) CmdGetMapped(intf string) (map[string]uint64, error) {
	ecmd := EthtoolCmd{
		Cmd: ETHTOOL_GSET,
	}

	var name [IFNAMSIZ]byte
	copy(name[:], []byte(intf))

	ifr := ifreq{
		ifr_name: name,
		ifr_data: uintptr(unsafe.Pointer(&ecmd)),
	}

	_, _, ep := syscall.Syscall(syscall.SYS_IOCTL, uintptr(e.fd),
		SIOCETHTOOL, uintptr(unsafe.Pointer(&ifr)))
	if ep != 0 {
		return nil, syscall.Errno(ep)
	}

	var result = make(map[string]uint64)

	// ref https://gist.github.com/drewolson/4771479
	// Golang Reflection Example
	ecmd.reflect(&result)

	var speedval uint32 = (uint32(ecmd.Speed_hi) << 16) |
		(uint32(ecmd.Speed) & 0xffff)
	result["speed"] = uint64(speedval)

	return result, nil
}
Example #12
0
func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) {
	fd, e := socketcall(_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
	if e != 0 {
		err = e
	}
	return
}
Example #13
0
//export callback_friend_message
func callback_friend_message(
	c_tox *C.Tox,
	c_friend_number C.uint32_t,
	c_message_type C.TOX_MESSAGE_TYPE,
	c_message *C.uint8_t,
	c_length C.size_t,
	c_user_data unsafe.Pointer,
) {
	// Initialize variables.
	tox := (*Tox)(c_user_data)
	friendNumber := uint32(c_friend_number)
	var messageType ToxMessageType
	switch c_message_type {
	case C.TOX_MESSAGE_TYPE_NORMAL:
		messageType = ToxMessageTypeNormal
	case C.TOX_MESSAGE_TYPE_ACTION:
		messageType = ToxMessageTypeAction
	}
	message := make([]byte, c_length)
	// Copy the chat message.
	if c_length > 0 {
		C.memcpy(
			unsafe.Pointer(&message[0]),
			unsafe.Pointer(c_message),
			c_length,
		)
	}
	// Register the callback.
	tox.onFriendMessage(tox, friendNumber, messageType, message)
}
Example #14
0
File: pq.go Project: dvarrazzo/pger
func connect(conninfo string) (*PgConn, error) {
	cs := C.CString(conninfo)
	defer C.free(unsafe.Pointer(cs))
	conn := C.PQconnectdb(cs)
	if C.PQstatus(conn) != C.CONNECTION_OK {
		cerr := C.PQerrorMessage(conn)
		err := fmt.Errorf("connection failed: %s", C.GoString(cerr))
		C.PQfinish(conn)
		return nil, err
	}

	// TODO: support other encodings?
	pname := C.CString("client_encoding")
	defer C.free(unsafe.Pointer(pname))
	cenc := C.PQparameterStatus(conn, pname)
	if cenc == nil {
		err := errors.New("connection failed: no client encoding")
		C.PQfinish(conn)
		return nil, err
	}
	if enc := C.GoString(cenc); enc != "UTF8" {
		err := fmt.Errorf(
			"connection failed: client encoding not supported: %s", enc)
		C.PQfinish(conn)
		return nil, err
	}

	// one-line error message
	C.PQsetErrorVerbosity(conn, C.PQERRORS_TERSE)

	return &PgConn{conn: conn, conninfo: conninfo}, nil
}
Example #15
0
//raise a pubkey to the power of a seckey
func ECDH(pub []byte, sec []byte) []byte {
	if len(sec) != 32 {
		log.Panic()
	}

	if len(pub) != 33 {
		log.Panic()
	}

	if VerifyPubkey(pub) != 1 {
		log.Printf("Invalid Pubkey")
		return nil
	}

	if VerifySeckey(sec) != 1 {
		log.Printf("Invalid Seckey")
	}

	var pub2 []byte = make([]byte, 33)
	copy(pub2[0:33], pub[0:33])

	var pub_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pub2[0]))
	var sec_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sec[0]))

	ret := C.secp256k1_ecdsa_pubkey_tweak_mul(
		pub_ptr, C.int(len(pub2)),
		sec_ptr,
	)

	if ret != 1 {
		return nil
	}

	return pub2
}
Example #16
0
// Marshal returns the binary encoding of the IPv4 header h.
func (h *Header) Marshal() ([]byte, error) {
	if h == nil {
		return nil, syscall.EINVAL
	}
	if h.Len < HeaderLen {
		return nil, errHeaderTooShort
	}
	hdrlen := HeaderLen + len(h.Options)
	b := make([]byte, hdrlen)
	b[0] = byte(Version<<4 | (hdrlen >> 2 & 0x0f))
	b[posTOS] = byte(h.TOS)
	if supportsNewIPInput {
		b[posTotalLen], b[posTotalLen+1] = byte(h.TotalLen>>8), byte(h.TotalLen)
		b[posFragOff], b[posFragOff+1] = byte(h.FragOff>>8), byte(h.FragOff)
	} else {
		*(*uint16)(unsafe.Pointer(&b[posTotalLen : posTotalLen+1][0])) = uint16(h.TotalLen)
		*(*uint16)(unsafe.Pointer(&b[posFragOff : posFragOff+1][0])) = uint16(h.FragOff)
	}
	b[posID], b[posID+1] = byte(h.ID>>8), byte(h.ID)
	b[posTTL] = byte(h.TTL)
	b[posProtocol] = byte(h.Protocol)
	b[posChecksum], b[posChecksum+1] = byte(h.Checksum>>8), byte(h.Checksum)
	if ip := h.Src.To4(); ip != nil {
		copy(b[posSrc:posSrc+net.IPv4len], ip[0:net.IPv4len])
	}
	if ip := h.Dst.To4(); ip != nil {
		copy(b[posDst:posDst+net.IPv4len], ip[0:net.IPv4len])
	} else {
		return nil, errMissingAddress
	}
	if len(h.Options) > 0 {
		copy(b[HeaderLen:], h.Options)
	}
	return b, nil
}
Example #17
0
func GenerateKeyPair() ([]byte, []byte) {

	pubkey_len := C.int(33)
	const seckey_len = 32

	var pubkey []byte = make([]byte, pubkey_len)
	var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0]))

	var ret C.int

new_seckey:
	var seckey []byte = RandByte(seckey_len)
	var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))

	ret = C.secp256k1_ecdsa_seckey_verify(seckey_ptr)

	if ret != 1 {
		goto new_seckey
	}

	//for C.secp256k1_ecdsa_seckey_verify(seckey_ptr) != 1 {
	//	seckey = RandByte(seckey_len)
	//	seckey_ptr = (*C.uchar)(unsafe.Pointer(&seckey[0]))
	//}

	ret = C.secp256k1_ecdsa_pubkey_create(
		pubkey_ptr, &pubkey_len,
		seckey_ptr, 1)

	if ret != 1 {
		goto new_seckey
	}

	return pubkey, seckey
}
Example #18
0
// ParseHeader parses b as an IPv4 header.
func ParseHeader(b []byte) (*Header, error) {
	if len(b) < HeaderLen {
		return nil, errHeaderTooShort
	}
	hdrlen := (int(b[0]) & 0x0f) << 2
	if hdrlen > len(b) {
		return nil, errBufferTooShort
	}
	h := &Header{}
	h.Version = int(b[0] >> 4)
	h.Len = hdrlen
	h.TOS = int(b[posTOS])
	if supportsNewIPInput {
		h.TotalLen = int(b[posTotalLen])<<8 | int(b[posTotalLen+1])
		h.FragOff = int(b[posFragOff])<<8 | int(b[posFragOff+1])
	} else {
		h.TotalLen = int(*(*uint16)(unsafe.Pointer(&b[posTotalLen : posTotalLen+1][0])))
		h.TotalLen += hdrlen
		h.FragOff = int(*(*uint16)(unsafe.Pointer(&b[posFragOff : posFragOff+1][0])))
	}
	h.ID = int(b[posID])<<8 | int(b[posID+1])
	h.TTL = int(b[posTTL])
	h.Protocol = int(b[posProtocol])
	h.Checksum = int(b[posChecksum])<<8 | int(b[posChecksum+1])
	h.Src = net.IPv4(b[posSrc], b[posSrc+1], b[posSrc+2], b[posSrc+3])
	h.Dst = net.IPv4(b[posDst], b[posDst+1], b[posDst+2], b[posDst+3])
	if hdrlen-HeaderLen > 0 {
		h.Options = make([]byte, hdrlen-HeaderLen)
		copy(h.Options, b[HeaderLen:])
	}
	return h, nil
}
Example #19
0
func (def *defUint64) value() (value interface{}, err error) {
	if def.isNullable {
		oraUint64Value := Uint64{IsNull: def.null < C.sb2(0)}
		if !oraUint64Value.IsNull {
			r := C.OCINumberToInt(
				def.rset.stmt.ses.srv.env.ocierr,      //OCIError              *err,
				&def.ociNumber,                        //const OCINumber       *number,
				C.uword(8),                            //uword                 rsl_length,
				C.OCI_NUMBER_UNSIGNED,                 //uword                 rsl_flag,
				unsafe.Pointer(&oraUint64Value.Value)) //void                  *rsl );
			if r == C.OCI_ERROR {
				err = def.rset.stmt.ses.srv.env.ociError()
			}
		}
		value = oraUint64Value
	} else {
		if def.null > C.sb2(-1) {
			var uint64Value uint64
			r := C.OCINumberToInt(
				def.rset.stmt.ses.srv.env.ocierr, //OCIError              *err,
				&def.ociNumber,                   //const OCINumber       *number,
				C.uword(8),                       //uword                 rsl_length,
				C.OCI_NUMBER_UNSIGNED,            //uword                 rsl_flag,
				unsafe.Pointer(&uint64Value))     //void                  *rsl );
			if r == C.OCI_ERROR {
				err = def.rset.stmt.ses.srv.env.ociError()
			}
			value = uint64Value
		}
	}
	return value, err
}
Example #20
0
func (self *Surface) ClipRectangleList() ([]Rectangle, Status) {
	list := C.cairo_copy_clip_rectangle_list(self.context)
	defer C.cairo_rectangle_list_destroy(list)
	rects := make([]Rectangle, int(list.num_rectangles))
	C.memcpy(unsafe.Pointer(&rects[0]), unsafe.Pointer(list.rectangles), C.size_t(list.num_rectangles*8))
	return rects, Status(list.status)
}
Example #21
0
func OpenWithFallback(fromCode string, toCode string, fallbackPolicy int) (ic *Iconv, err error) {
	var pIconv C.iconv_t

	toCodeCharPtr := C.CString(toCode)
	defer C.free(unsafe.Pointer(toCodeCharPtr))
	fromCodeCharPtr := C.CString(fromCode)
	defer C.free(unsafe.Pointer(fromCodeCharPtr))

	pIconv, err = C.iconv_open(toCodeCharPtr, fromCodeCharPtr)
	if err == nil {
		if pIconv == nil {
			err = NilIconvPointer
			return
		}
		if fallbackPolicy == DISCARD_UNRECOGNIZED {
			ic = &Iconv{pIconv: pIconv, fallbackPolicy: fallbackPolicy, fallback: fallbackDiscardUnrecognized}
		} else if fallbackPolicy == KEEP_UNRECOGNIZED {
			ic = &Iconv{pIconv: pIconv, fallbackPolicy: fallbackPolicy, fallback: fallbackKeepIntactUnrecognized}
		} else if fallbackPolicy == NEXT_ENC_UNRECOGNIZED {
			ic = &Iconv{pIconv: pIconv, fallbackPolicy: fallbackPolicy}
		} else {
			err = InvalidFallbackPolicy
		}
	}
	return
}
Example #22
0
func (self *Surface) Native() (surface, context uintptr) {

	surface = uintptr(unsafe.Pointer(self.surface))
	context = uintptr(unsafe.Pointer(self.context))

	return
}
Example #23
0
func (z *zeroconf) removePrinter(name string) error {
	z.spMutex.Lock()
	defer z.spMutex.Unlock()

	r, exists := z.printers[name]
	if !exists {
		return fmt.Errorf("printer %s cannot be updated for Avahi publishing; it was never added", name)
	}

	if z.state == C.AVAHI_CLIENT_S_RUNNING && r.group != nil {
		C.avahi_threaded_poll_lock(z.threadedPoll)
		defer C.avahi_threaded_poll_unlock(z.threadedPoll)

		var errstr *C.char
		C.removeAvahiGroup(z.threadedPoll, r.group, &errstr)
		if errstr != nil {
			err := errors.New(C.GoString(errstr))
			C.free(unsafe.Pointer(errstr))
			return err
		}
	}

	C.free(unsafe.Pointer(r.name))

	delete(z.printers, name)
	return nil
}
Example #24
0
//generates deterministic keypair with weak SHA256 hash of seed
//internal use only
//be extremely careful with golang slice semantics
func generateDeterministicKeyPair(seed []byte) ([]byte, []byte) {
	if seed == nil {
		log.Panic()
	}

	pubkey_len := C.int(33)
	const seckey_len = 32

	var pubkey []byte = make([]byte, pubkey_len)
	var seckey []byte = make([]byte, seckey_len)

	var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
	var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))

new_seckey:
	seed = SumSHA256(seed[0:32])
	copy(seckey[0:32], seed[0:32])
	if C.secp256k1_ecdsa_seckey_verify(seckey_ptr) != 1 {
		goto new_seckey //rehash seckey until it succeeds, almost never happens
	}

	ret := C.secp256k1_ecdsa_pubkey_create(
		pubkey_ptr, &pubkey_len,
		seckey_ptr, 1)

	if ret != 1 {
		log.Panic("secp256k1-g0, generateDeterministicKeyPair, pubkey generation failing for valid seckey")
	}

	return pubkey, seckey
}
Example #25
0
// May run with m.p==nil, so write barriers are not allowed.
//go:nowritebarrier
func newosproc(mp *m, _ unsafe.Pointer) {
	var (
		attr pthreadattr
		oset sigset
		tid  pthread
		ret  int32
		size uint64
	)

	if pthread_attr_init(&attr) != 0 {
		throw("pthread_attr_init")
	}
	if pthread_attr_setstack(&attr, 0, 0x200000) != 0 {
		throw("pthread_attr_setstack")
	}
	if pthread_attr_getstack(&attr, unsafe.Pointer(&mp.g0.stack.hi), &size) != 0 {
		throw("pthread_attr_getstack")
	}
	mp.g0.stack.lo = mp.g0.stack.hi - uintptr(size)
	if pthread_attr_setdetachstate(&attr, _PTHREAD_CREATE_DETACHED) != 0 {
		throw("pthread_attr_setdetachstate")
	}

	// Disable signals during create, so that the new thread starts
	// with signals disabled.  It will enable them in minit.
	sigprocmask(_SIG_SETMASK, &sigset_all, &oset)
	ret = pthread_create(&tid, &attr, funcPC(tstart_sysvicall), unsafe.Pointer(mp))
	sigprocmask(_SIG_SETMASK, &oset, nil)
	if ret != 0 {
		print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", ret, ")\n")
		throw("newosproc")
	}
}
Example #26
0
//generate signature in repeatable way
func SignDeterministic(msg []byte, seckey []byte, nonce_seed []byte) []byte {
	nonce := SumSHA256(nonce_seed) //deterministicly generate nonce

	var sig []byte = make([]byte, 65)
	var recid C.int

	var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0]))
	var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))
	var nonce_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&nonce[0]))
	var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0]))

	if C.secp256k1_ecdsa_seckey_verify(seckey_ptr) != C.int(1) {
		log.Panic("Invalid secret key")
	}

	ret := C.secp256k1_ecdsa_sign_compact(
		msg_ptr, C.int(len(msg)),
		sig_ptr,
		seckey_ptr,
		nonce_ptr,
		&recid)

	sig[64] = byte(int(recid))

	if int(recid) > 4 {
		log.Panic()
	}

	if ret != 1 {
		return SignDeterministic(msg, seckey, nonce_seed) //nonce invalid,retry
	}

	return sig
}
Example #27
0
func Nanosleep(time *Timespec, leftover *Timespec) (err error) {
	_, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0)
	if e1 != 0 {
		err = errnoErr(e1)
	}
	return
}
Example #28
0
//recovers the public key from the signature
//recovery of pubkey means correct signature
func RecoverPubkey(msg []byte, sig []byte) []byte {
	if len(sig) != 65 {
		log.Panic()
	}

	var pubkey []byte = make([]byte, 33)

	var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0]))
	var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0]))
	var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0]))

	var pubkeylen C.int

	ret := C.secp256k1_ecdsa_recover_compact(
		msg_ptr, C.int(len(msg)),
		sig_ptr,
		pubkey_ptr, &pubkeylen,
		C.int(1), C.int(sig[64]),
	)

	if ret == 0 || int(pubkeylen) != 33 {
		return nil
	}

	return pubkey
}
Example #29
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
}
Example #30
-1
// Delete the actual bridge device.
func DeleteBridge(name string) error {
	s, err := getIfSocket()
	if err != nil {
		return err
	}
	defer syscall.Close(s)

	nameBytePtr, err := syscall.BytePtrFromString(name)
	if err != nil {
		return err
	}

	var ifr ifreqFlags
	copy(ifr.IfrnName[:len(ifr.IfrnName)-1], []byte(name))
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s),
		syscall.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifr))); err != 0 {
		return err
	}

	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s),
		SIOC_BRDELBR, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 {
		return err
	}
	return nil
}