Exemple #1
0
// Visit visit ast tree
func (compiler *Compiler) Visit(codeGen Visitor) (err error) {

	defer func() {
		if e := recover(); e != nil {

			gserr, ok := e.(gserrors.GSError)

			if ok {
				err = gserr
			} else {
				err = gserrors.Newf(e.(error), "catch unknown error")
			}
		}
	}()

	gen := &_Visitor{
		Log:      gslogger.Get("codegen"),
		codeGen:  codeGen,
		module:   compiler.module,
		compiler: compiler,
	}

	gen.visit()

	return
}
Exemple #2
0
func (storage *_Storage) Read(version uint64) (val *DBValue, ok bool) {

	key := fmt.Sprintf("%s:%d", storage.key, version%uint64(storage.valen))

	buff, err := storage.db.Get([]byte(key), nil)

	if err != nil {
		if err != leveldb.ErrNotFound {
			storage.E("get %s -> value \n%s", key, gserrors.Newf(err, ""))
		}

		return nil, false
	}

	if buff == nil {
		return nil, false
	}

	val, err = ReadDBValue(bytes.NewBuffer(buff))

	if err != nil {
		storage.E("unmarshal %s -> %s error\n%s", key, buff, err)
		return nil, false
	}

	return val, true
}
Exemple #3
0
// NewCodeGen .
func NewCodeGen(rootpath string, skips []string) (gslang.Visitor, error) {

	codeGen := &_CodeGen{
		Log:      gslogger.Get("gen4go"),
		rootpath: rootpath,
		prefix:   make(map[string]string),
	}

	for _, skip := range skips {
		exp, err := regexp.Compile(skip)

		if err != nil {
			return nil, gserrors.Newf(err, "invalid skip regex string :%s", skip)
		}

		codeGen.skips = append(codeGen.skips, exp)
	}

	funcs := template.FuncMap{
		"title":           codeGen.title,
		"title2":          strings.Title,
		"enumFields":      codeGen.enumFields,
		"typeName":        codeGen.typeName,
		"enumRead":        codeGen.enumRead,
		"enumWrite":       codeGen.enumWrite,
		"fieldDecl":       codeGen.fieldDecl,
		"defaultVal":      codeGen.defaultVal,
		"marshalField":    codeGen.marshalField,
		"unmarshalField":  codeGen.unmarshalField,
		"methodDecl":      codeGen.methodDecl,
		"rpcMethodDecl":   codeGen.rpcMethodDecl,
		"unmarshalParam":  codeGen.unmarshalParam,
		"marshalParam":    codeGen.marshalParam,
		"methodCall":      codeGen.methodCall,
		"marshalReturn":   codeGen.marshalReturn,
		"unmarshalReturn": codeGen.unmarshalReturn,
		"notVoid":         gslang.NotVoid,
		"isPOD":           gslang.IsPOD,
		"isAsync":         gslang.IsAsync,
		"isException":     gslang.IsException,
		"enumSize":        gslang.EnumSize,
		"enumType": func(typeDecl ast.Type) string {
			return builtin[gslang.EnumType(typeDecl)]
		},
		"builtin":       gslang.IsBuiltin,
		"marshalParams": codeGen.marshalParams,
		"callback":      codeGen.callback,
		"tagValue":      codeGen.tagValue,
	}

	tpl, err := template.New("t4objc").Funcs(funcs).Parse(t4objc)

	if err != nil {
		return nil, err
	}

	codeGen.tpl = tpl

	return codeGen, nil
}
Exemple #4
0
//Read read whole package from stream
func Read(reader io.Reader) ([]byte, error) {
	var header [2]byte

	if _, err := io.ReadFull(reader, header[:]); err != nil {
		return nil, gserrors.Newf(err, "read package length error")
	}

	length := binary.LittleEndian.Uint16(header[:])

	buff := make([]byte, length)

	if _, err := io.ReadFull(reader, buff); err != nil {
		return nil, gserrors.Newf(err, "read package body(%d) error", length)
	}

	return buff, nil
}
Exemple #5
0
//ReadString read string
func ReadString(reader Reader) (string, error) {
	len, err := ReadUInt16(reader)

	if err != nil {
		return "", gserrors.Newf(err, "read string len error")
	}

	buff := make([]byte, len)

	_, err = reader.Read(buff)

	if err != nil {
		return "", gserrors.Newf(err, "read string[%d] body error", len)
	}

	return string(buff), nil
}
Exemple #6
0
//ReadByte read byte from Reader interface
func ReadByte(reader Reader) (byte, error) {
	val, err := reader.ReadByte()

	if err != nil {
		return 0, gserrors.Newf(err, "read byte error")
	}

	return val, err
}
Exemple #7
0
//ReadBytes read bytes from reader
func ReadBytes(reader Reader, val []byte) error {
	_, err := reader.Read(val)

	if err != nil {
		return gserrors.Newf(err, "read bytes[%d] error", len(val))
	}

	return nil
}
Exemple #8
0
func (context *_Context) onPanic(err error) {
	defer func() {

		if e := recover(); e != nil {
			err = gserrors.Newf(nil, "catch unhandle error :%s", e)
		}
	}()

	context.handler.Panic(context, err)
}
Exemple #9
0
//ReadUInt16 read uint16 from Reader interface
func ReadUInt16(reader Reader) (uint16, error) {
	buf := make([]byte, 2)

	_, err := reader.Read(buf)

	if err != nil {
		return 0, gserrors.Newf(err, "read uint16 error")
	}

	return uint16(buf[0]) | uint16(buf[1])<<8, nil
}
Exemple #10
0
//ReadUInt32 read uint32 from Reader interface
func ReadUInt32(reader Reader) (uint32, error) {
	buf := make([]byte, 4)

	_, err := reader.Read(buf)

	if err != nil {
		return 0, gserrors.Newf(err, "read uint32 error")
	}

	return uint32(buf[3])<<24 | uint32(buf[2])<<16 | uint32(buf[1])<<8 | uint32(buf[0]), nil
}
Exemple #11
0
func (sink *_Sink) dispatchResponse(response *Response) {
	sink.Lock()
	defer sink.Unlock()

	if promise, ok := sink.promises[response.ID]; ok {
		go promise.Notify(response, nil)
		delete(sink.promises, response.ID)
		return
	}

	sink.W("%s unhandle response(%d) %s", sink.name, response.ID, gserrors.Newf(nil, ""))
}
Exemple #12
0
func (context *_Context) onMessageReceived(message *Message) (ret *Message, err error) {

	defer func() {

		if e := recover(); e != nil {
			err = gserrors.Newf(nil, "catch unhandle error :%s", e)
		}
	}()

	ret, err = context.handler.MessageReceived(context, message)

	return
}
Exemple #13
0
// NewCodeGen .
func NewCodeGen(rootpath string, skips []string) (gslang.Visitor, error) {

	codeGen := &_CodeGen{
		Log:      gslogger.Get("gen4go"),
		rootpath: rootpath,
	}

	for _, skip := range skips {
		exp, err := regexp.Compile(skip)

		if err != nil {
			return nil, gserrors.Newf(err, "invalid skip regex string :%s", skip)
		}

		codeGen.skips = append(codeGen.skips, exp)
	}

	funcs := template.FuncMap{
		"title": strings.Title,
		"enumType": func(typeDecl ast.Type) string {
			return builtin[gslang.EnumType(typeDecl)]
		},
		"notVoid":     gslang.NotVoid,
		"isPOD":       gslang.IsPOD,
		"isAsync":     gslang.IsAsync,
		"isException": gslang.IsException,
		"enumSize":    gslang.EnumSize,
		"builtin":     gslang.IsBuiltin,
		"typeName":    codeGen.typeName,
		"defaultVal":  codeGen.defaultVal,
		"readType":    codeGen.readType,
		"writeType":   codeGen.writeType,
		"params":      codeGen.params,
		"returnParam": codeGen.returnParam,
		"callArgs":    codeGen.callArgs,
		"returnArgs":  codeGen.returnArgs,
		"tagValue":    codeGen.tagValue,
	}

	tpl, err := template.New("gen4go").Funcs(funcs).Parse(tpl4go)

	if err != nil {
		return nil, err
	}

	codeGen.tpl = tpl

	return codeGen, nil
}
Exemple #14
0
//ReadUInt64 read uint16 from Reader interface
func ReadUInt64(reader Reader) (uint64, error) {
	buf := make([]byte, 8)
	_, err := reader.Read(buf)

	if err != nil {
		return 0, gserrors.Newf(err, "read uint64 error")
	}

	var ret uint64

	for i, v := range buf {
		ret |= uint64(v) << uint(i*8)
	}

	return ret, nil
}
Exemple #15
0
// Write write whole input data to stream
func Write(writer io.Writer, buff []byte) (int, error) {
	length := len(buff)

	if length > math.MaxUint16 {
		return 0, gserrors.Newf(ErrEncode, "send package out of range :%d", length)
	}

	var buf [2]byte

	binary.LittleEndian.PutUint16(buf[:], uint16(length))

	length, err := writer.Write(buf[:])

	if err != nil {
		return length, err
	}

	return writer.Write(buff)
}
Exemple #16
0
func (context *_Context) onUnregister() {
	defer func() {

		if e := recover(); e != nil {
			context.W(
				"call handler(%s) Unregister method error\n%s",
				context.Name(),
				gserrors.Newf(nil, "catch unhandle error :%s", e),
			)
		}
	}()

	if context.state == handlerUnregister {
		return
	}

	context.handler.Unregister(context)

	context.state = handlerUnregister
}
Exemple #17
0
// TCPListen .
func TCPListen(acceptor *Acceptor, laddr string) error {

	listener, err := net.Listen("tcp", laddr)

	if err != nil {
		return err
	}

	for {
		conn, err := listener.Accept()

		if err != nil {
			return gserrors.Newf(err, "tcp(%s) accept error", laddr)
		}

		acceptor.V("accept connection(%s)", conn.RemoteAddr())

		acceptor.Accept(conn.RemoteAddr().String(), conn)
	}
}
Exemple #18
0
func (context *_Context) onInactive() {
	defer func() {

		if e := recover(); e != nil {
			context.W(
				"call handler(%s) onInactive method error\n%s",
				context.Name(),
				gserrors.Newf(nil, "catch unhandle error :%s", e),
			)
		}

	}()

	if context.state != handlerActived {
		return
	}

	context.handler.Inactive(context)

	context.state = handlerRegister
}
Exemple #19
0
func (context *_Context) onActive() (err error) {

	defer func() {

		if e := recover(); e != nil {
			err = gserrors.Newf(nil, "catch unhandle error :%s", e)
		}
	}()

	if context.state != handlerRegister {
		return nil
	}

	err = context.handler.Active(context)

	if err == nil || err == ErrSkip {
		context.state = handlerActived
	}

	return
}
Exemple #20
0
// NewCodeGen .
func NewCodeGen(rootpath string, skips []string) (gslang.Visitor, error) {

	codeGen := &_CodeGen{
		Log:      gslogger.Get("gen4go"),
		rootpath: rootpath,
	}

	for _, skip := range skips {
		exp, err := regexp.Compile(skip)

		if err != nil {
			return nil, gserrors.Newf(err, "invalid skip regex string :%s", skip)
		}

		codeGen.skips = append(codeGen.skips, exp)
	}

	funcs := template.FuncMap{
		"exception": exception,
		"title":     strings.Title,
		"tableName": func(typeDecl ast.Type) string {
			if gslang.IsException(typeDecl) {
				return exception(strings.Title(typeDecl.Name()))
			}

			return strings.Title(typeDecl.Name())
		},
		"methodName":  methodName,
		"fieldName":   fieldname,
		"enumFields":  codeGen.enumFields,
		"notVoid":     gslang.NotVoid,
		"isPOD":       gslang.IsPOD,
		"isAsync":     gslang.IsAsync,
		"isException": gslang.IsException,
		"enumSize":    gslang.EnumSize,
		"enumType": func(typeDecl ast.Type) string {
			return builtin[gslang.EnumType(typeDecl)]
		},
		"builtin":         gslang.IsBuiltin,
		"typeName":        codeGen.typeName,
		"objTypeName":     codeGen.objTypeName,
		"defaultVal":      codeGen.defaultVal,
		"readType":        codeGen.readType,
		"writeType":       codeGen.writeType,
		"params":          codeGen.params,
		"returnParam":     codeGen.returnParam,
		"callArgs":        codeGen.callArgs,
		"returnArgs":      codeGen.returnArgs,
		"marshalField":    codeGen.marshalfield,
		"unmarshalField":  codeGen.unmarshalfield,
		"unmarshalParam":  codeGen.unmarshalParam,
		"methodcall":      codeGen.methodcall,
		"marshalParam":    codeGen.marshalParam,
		"marshalReturn":   codeGen.marshalReturn,
		"methodRPC":       codeGen.methodRPC,
		"marshalParams":   codeGen.marshalParams,
		"callback":        codeGen.callback,
		"unmarshalReturn": codeGen.unmarshalReturn,
		"constructor":     codeGen.constructor,
		"tagValue":        codeGen.tagValue,
	}

	tpl, err := template.New("t4java").Funcs(funcs).Parse(t4java)

	if err != nil {
		return nil, err
	}

	codeGen.tpl = tpl

	return codeGen, nil
}
Exemple #21
0
func (handler *_CryptoClient) MessageReceived(context gorpc.Context, message *gorpc.Message) (*gorpc.Message, error) {

	if message.Code == gorpc.CodeHeartbeat {
		return message, nil
	}

	if handler.block == nil {

		handler.V("expect handshake accept")

		if message.Code != gorpc.CodeAccept {

			handler.E("unexpect message(%s)", message.Code)

			context.Close()

			return nil, gserrors.Newf(gorpc.ErrRPC, "expect handshake(Accept) but got(%s)", message.Code)
		}

		handler.V("parse handshake accept")

		val, ok := new(big.Int).SetString(string(message.Content), 0)

		if !ok {
			context.Close()
			return nil, gserrors.Newf(gorpc.ErrRPC, "parse Accept#Content as big.Int error")
		}

		key := make([]byte, des.BlockSize)

		keyval := handler.dhKey.Gen(val).Uint64()

		binary.BigEndian.PutUint64(key[:8], keyval)

		handler.V("shared key \n\t%d\n\t%v ", keyval, key)

		block, err := des.NewCipher(key)

		if err != nil {
			context.Close()
			return nil, gserrors.Newf(err, "create new des Cipher error")
		}

		handler.block = block

		handler.V("%s handshake -- success", context.Name())

		context.FireActive()

		for _, message := range handler.cached {
			message, _ = handler.MessageSending(context, message)
			context.Send(message)
		}

		handler.cached = nil

		return nil, nil
	}

	if message.Code == gorpc.CodeHeartbeat {
		return message, nil
	}

	blocksize := handler.block.BlockSize()

	if len(message.Content)%blocksize != 0 {
		context.Close()
		return nil, gserrors.Newf(gorpc.ErrRPC, "%s invalid encrypt data", context)
	}

	blocks := len(message.Content) / blocksize

	for i := 0; i < blocks; i++ {
		offset := i * blocksize
		v := message.Content[offset : offset+blocksize]
		handler.block.Decrypt(v, v)
	}

	message.Content = PKCS5UnPadding(message.Content)

	return message, nil
}
Exemple #22
0
func (handler *_CryptoServer) MessageReceived(context gorpc.Context, message *gorpc.Message) (*gorpc.Message, error) {

	if message.Code == gorpc.CodeHeartbeat {
		return message, nil
	}

	if handler.block == nil {

		handler.V("expect WhoAmI message")
		// expect whoAmI message
		if message.Code != gorpc.CodeWhoAmI {
			context.Close()
			return nil, gserrors.Newf(gorpc.ErrRPC, "expect WhoAmI message but got(%s)", message.Code)
		}

		handler.V("parse WhoAmI message")

		whoAmI, err := gorpc.ReadWhoAmI(bytes.NewBuffer(message.Content))

		if err != nil {
			context.Close()
			return nil, err
		}

		val, ok := new(big.Int).SetString(string(whoAmI.Context), 0)

		if !ok {
			context.Close()
			return nil, gserrors.Newf(gorpc.ErrRPC, "parse WhoAmI#Context as big.Int error")
		}

		dhKey, err := handler.resovler.Resolve(whoAmI.ID)

		if err != nil {
			context.Close()
			return nil, err
		}

		message.Code = gorpc.CodeAccept

		message.Content = []byte(dhKey.Exchange().String())

		context.Send(message)

		key := make([]byte, des.BlockSize)

		keyval := dhKey.Gen(val).Uint64()

		binary.BigEndian.PutUint64(key[:8], keyval)

		handler.V("shared key \n\t%d\n\t%v ", keyval, key)

		block, err := des.NewCipher(key)

		if err != nil {
			context.Close()
			return nil, gserrors.Newf(err, "create new des Cipher error")
		}

		handler.block = block

		handler.device = whoAmI.ID

		context.FireActive()

		for _, message := range handler.cached {
			message, _ = handler.MessageSending(context, message)
			context.Send(message)
		}

		handler.cached = nil

		handler.V("%s handshake -- success", context.Name())

		return nil, nil

	}

	blocksize := handler.block.BlockSize()

	if len(message.Content)%blocksize != 0 {
		context.Close()
		return nil, gserrors.Newf(gorpc.ErrRPC, "invalid encrypt data")
	}

	blocks := len(message.Content) / blocksize

	for i := 0; i < blocks; i++ {
		offset := i * blocksize
		v := message.Content[offset : offset+blocksize]
		handler.block.Decrypt(v, v)
	}

	message.Content = PKCS5UnPadding(message.Content)

	return message, nil
}
Exemple #23
0
func (lexer *Lexer) newerror(fmtstring string, args ...interface{}) error {
	return gserrors.Newf(ErrLexer, "[lexer] %s\n\t%s", fmt.Sprintf(fmtstring, args...), lexer.position)
}