diff --git a/Gopkg.lock b/Gopkg.lock index 13bbba3..938fbe3 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -371,7 +371,7 @@ [[projects]] branch = "master" - digest = "1:67e18f9bd60b62a52f4d917fa2e73e6f4e1cb407c75652d2fc47b85d82f28e78" + digest = "1:e74e65997eff2d82c090800fe08eec730ae9d12ea8c8494d178348422e2d1a8e" name = "github.com/topfreegames/pitaya" packages = [ ".", @@ -410,15 +410,7 @@ "worker", ] pruneopts = "UT" - revision = "eab89799e12c6233a6d1abacb757e52f9ec2efd6" - -[[projects]] - digest = "1:a988307f0c4c8015c00cc122433879cf8eb4da05bd31b2f578795531a7815b13" - name = "github.com/topfreegames/viaproxy" - packages = ["."] - pruneopts = "UT" - revision = "05f07d250022488417546d8056f49856b253c712" - version = "v0.1.2" + revision = "dc28e42f6eb0f4f3ca2d00f7eebfe986a5964bc9" [[projects]] branch = "master" diff --git a/vendor/github.com/topfreegames/pitaya/.travis.yml b/vendor/github.com/topfreegames/pitaya/.travis.yml index fe0c2c8..81abc14 100644 --- a/vendor/github.com/topfreegames/pitaya/.travis.yml +++ b/vendor/github.com/topfreegames/pitaya/.travis.yml @@ -1,6 +1,6 @@ language: go go: -- "1.10" +- "1.11" sudo: false services: - docker diff --git a/vendor/github.com/topfreegames/pitaya/Gopkg.lock b/vendor/github.com/topfreegames/pitaya/Gopkg.lock index 64ca771..3f577c7 100644 --- a/vendor/github.com/topfreegames/pitaya/Gopkg.lock +++ b/vendor/github.com/topfreegames/pitaya/Gopkg.lock @@ -580,14 +580,6 @@ revision = "debd68e29f6123083fb906c7a6352c748203538a" version = "v0.0.1" -[[projects]] - digest = "1:a157dc7b8f23c258b204ff81469c91136a45fd90284fbb6387fea23bd3e48607" - name = "github.com/topfreegames/viaproxy" - packages = ["."] - pruneopts = "UT" - revision = "8724385082be8dce5bbd2c1c00cf80e2a71075bf" - version = "v0.1.1" - [[projects]] digest = "1:a65ad5ffa268f4591efad04749e128bde6a80cbbc128688b6327fec461a61a38" name = "github.com/uber/jaeger-client-go" @@ -796,7 +788,6 @@ "github.com/stretchr/testify/assert", "github.com/stretchr/testify/require", "github.com/topfreegames/go-workers", - "github.com/topfreegames/viaproxy", "github.com/uber/jaeger-client-go", "github.com/uber/jaeger-client-go/config", "golang.org/x/net/context", diff --git a/vendor/github.com/topfreegames/pitaya/README.md b/vendor/github.com/topfreegames/pitaya/README.md index 05495c9..5db8a3f 100644 --- a/vendor/github.com/topfreegames/pitaya/README.md +++ b/vendor/github.com/topfreegames/pitaya/README.md @@ -82,6 +82,10 @@ This command will run both unit and e2e tests. * [nano](https://github.com/lonnng/nano) authors for building the framework pitaya is based on. * [pomelo](https://github.com/NetEase/pomelo) authors for the inspiration on the distributed design and protocol +## Security + +If you have found a security vulnerability, please email security@tfgco.com + ## Resources - Other pitaya-related projects diff --git a/vendor/github.com/topfreegames/pitaya/acceptor/tcp_acceptor.go b/vendor/github.com/topfreegames/pitaya/acceptor/tcp_acceptor.go index c0582f7..ebbe429 100644 --- a/vendor/github.com/topfreegames/pitaya/acceptor/tcp_acceptor.go +++ b/vendor/github.com/topfreegames/pitaya/acceptor/tcp_acceptor.go @@ -26,7 +26,6 @@ import ( "github.com/topfreegames/pitaya/constants" "github.com/topfreegames/pitaya/logger" - "github.com/topfreegames/viaproxy" ) // TCPAcceptor struct @@ -122,12 +121,6 @@ func (a *TCPAcceptor) serve() { continue } - pcn, err := viaproxy.Wrap(conn) - if err != nil { - logger.Log.Errorf("conn wrap error: %q\n", err) - continue - } - - a.connChan <- pcn + a.connChan <- conn } } diff --git a/vendor/github.com/topfreegames/pitaya/app.go b/vendor/github.com/topfreegames/pitaya/app.go index f900236..c7f30ef 100644 --- a/vendor/github.com/topfreegames/pitaya/app.go +++ b/vendor/github.com/topfreegames/pitaya/app.go @@ -575,11 +575,14 @@ func Documentation(getPtrNames bool) (map[string]interface{}, error) { // port into metadata func AddGRPCInfoToMetadata( metadata map[string]string, - region, host, externalHost, port string, + region string, + host, port string, + externalHost, externalPort string, ) map[string]string { metadata[constants.GRPCHostKey] = host - metadata[constants.GRPCExternalHostKey] = externalHost metadata[constants.GRPCPortKey] = port + metadata[constants.GRPCExternalHostKey] = externalHost + metadata[constants.GRPCExternalPortKey] = externalPort metadata[constants.RegionKey] = region return metadata } diff --git a/vendor/github.com/topfreegames/pitaya/client/protoclient.go b/vendor/github.com/topfreegames/pitaya/client/protoclient.go index ae0a42d..b6a27fd 100644 --- a/vendor/github.com/topfreegames/pitaya/client/protoclient.go +++ b/vendor/github.com/topfreegames/pitaya/client/protoclient.go @@ -42,10 +42,10 @@ import ( // Command struct. Save the input and output type and proto descriptor for each // one. type Command struct { - input string // input command name - output string // output command name - inputMsg *dynamic.Message - outputMsg *dynamic.Message + input string // input command name + output string // output command name + inputMsgDescriptor *desc.MessageDescriptor + outputMsgDescriptor *desc.MessageDescriptor } // ProtoBufferInfo save all commands from a server. @@ -56,14 +56,14 @@ type ProtoBufferInfo struct { // ProtoClient struct type ProtoClient struct { Client - descriptorsNames map[string]bool - info ProtoBufferInfo - docsRoute string - descriptorsRoute string - IncomingMsgChan chan *message.Message - expectedInput *dynamic.Message - ready bool - closeChan chan bool + descriptorsNames map[string]bool + info ProtoBufferInfo + docsRoute string + descriptorsRoute string + IncomingMsgChan chan *message.Message + expectedInputDescriptor *desc.MessageDescriptor + ready bool + closeChan chan bool } // MsgChannel return the incoming message channel @@ -97,7 +97,7 @@ func unpackDescriptor(compressedDescriptor []byte) (*protobuf.FileDescriptorProt // protobuffer from this data and associates it to the message. func (pc *ProtoClient) buildProtosFromDescriptor(descriptorArray []*protobuf.FileDescriptorProto) error { - descriptorsMap := make(map[string]*dynamic.Message) + descriptorsMap := make(map[string]*desc.MessageDescriptor) descriptors, err := desc.CreateFileDescriptors(descriptorArray) if err != nil { @@ -108,17 +108,17 @@ func (pc *ProtoClient) buildProtosFromDescriptor(descriptorArray []*protobuf.Fil for _, v := range descriptors { message := v.FindMessage(name) if message != nil { - descriptorsMap[name] = dynamic.NewMessage(message) + descriptorsMap[name] = message } } } for name, cmd := range pc.info.Commands { if msg, ok := descriptorsMap[cmd.input]; ok { - pc.info.Commands[name].inputMsg = msg + pc.info.Commands[name].inputMsgDescriptor = msg } if msg, ok := descriptorsMap[cmd.output]; ok { - pc.info.Commands[name].outputMsg = msg + pc.info.Commands[name].outputMsgDescriptor = msg } } @@ -365,13 +365,29 @@ func (pc *ProtoClient) waitForData() { select { case response := <-pc.Client.IncomingMsgChan: - inputMsg := pc.expectedInput + inputMsg := dynamic.NewMessage(pc.expectedInputDescriptor) msg, ok := pc.info.Commands[response.Route] if ok { - inputMsg = msg.outputMsg + inputMsg = dynamic.NewMessage(msg.outputMsgDescriptor) } else { - pc.expectedInput = nil + pc.expectedInputDescriptor = nil + } + + if response.Err { + errMsg := &protos.Error{} + err := proto.Unmarshal(response.Data, errMsg) + if err != nil { + logger.Log.Errorf("Erro decode error data: %s", string(response.Data)) + continue + } + response.Data, err = json.Marshal(errMsg) + if err != nil { + logger.Log.Errorf("Erro encode error to json: %s", string(response.Data)) + continue + } + pc.IncomingMsgChan <- response + continue } if inputMsg == nil { @@ -478,19 +494,20 @@ func (pc *ProtoClient) SendRequest(route string, data []byte) (uint, error) { } if cmd, ok := pc.info.Commands[route]; ok { - if len(data) < 0 || string(data) == "{}" || cmd.inputMsg == nil { - pc.expectedInput = cmd.outputMsg + if len(data) < 0 || string(data) == "{}" || cmd.inputMsgDescriptor == nil { + pc.expectedInputDescriptor = cmd.outputMsgDescriptor data = data[:0] return pc.Client.SendRequest(route, data) } - if err := cmd.inputMsg.UnmarshalJSON(data); err != nil { + inputMsg := dynamic.NewMessage(cmd.inputMsgDescriptor) + if err := inputMsg.UnmarshalJSON(data); err != nil { return 0, err } - realdata, err := cmd.inputMsg.Marshal() + realdata, err := inputMsg.Marshal() if err != nil { return 0, err } - pc.expectedInput = cmd.outputMsg + pc.expectedInputDescriptor = cmd.outputMsgDescriptor return pc.Client.SendRequest(route, realdata) } @@ -501,11 +518,12 @@ func (pc *ProtoClient) SendRequest(route string, data []byte) (uint, error) { func (pc *ProtoClient) SendNotify(route string, data []byte) error { if cmd, ok := pc.info.Commands[route]; ok { - err := cmd.inputMsg.UnmarshalJSON(data) + inputMsg := dynamic.NewMessage(cmd.inputMsgDescriptor) + err := inputMsg.UnmarshalJSON(data) if err != nil { return err } - realdata, err := cmd.inputMsg.Marshal() + realdata, err := inputMsg.Marshal() if err != nil { return err } diff --git a/vendor/github.com/topfreegames/pitaya/cluster/grpc_rpc_client.go b/vendor/github.com/topfreegames/pitaya/cluster/grpc_rpc_client.go index ced0bce..3e1930f 100644 --- a/vendor/github.com/topfreegames/pitaya/cluster/grpc_rpc_client.go +++ b/vendor/github.com/topfreegames/pitaya/cluster/grpc_rpc_client.go @@ -30,6 +30,7 @@ import ( "github.com/topfreegames/pitaya/config" "github.com/topfreegames/pitaya/conn/message" "github.com/topfreegames/pitaya/constants" + pcontext "github.com/topfreegames/pitaya/context" pitErrors "github.com/topfreegames/pitaya/errors" "github.com/topfreegames/pitaya/interfaces" "github.com/topfreegames/pitaya/logger" @@ -105,7 +106,18 @@ func (gs *GRPCClient) Call(ctx context.Context, rpcType protos.RPCType, route *r } if c, ok := gs.clientMap.Load(server.ID); ok { ctxT, done := context.WithTimeout(ctx, gs.reqTimeout) - defer done() + + defer func() { + if gs.metricsReporters != nil { + startTime := time.Now() + ctxT = pcontext.AddToPropagateCtx(ctxT, constants.StartTimeKey, startTime.UnixNano()) + ctxT = pcontext.AddToPropagateCtx(ctxT, constants.RouteKey, route.String()) + errored := err != nil + metrics.ReportTimingFromCtx(ctx, gs.metricsReporters, "rpc", errored) + } + done() + }() + res, err := c.(protos.PitayaClient).Call(ctxT, &req) if err != nil { return nil, err diff --git a/vendor/github.com/topfreegames/pitaya/constants/errors.go b/vendor/github.com/topfreegames/pitaya/constants/errors.go index 4221315..42b1d85 100644 --- a/vendor/github.com/topfreegames/pitaya/constants/errors.go +++ b/vendor/github.com/topfreegames/pitaya/constants/errors.go @@ -41,6 +41,7 @@ var ( ErrGroupNotFound = errors.New("group not found") ErrIllegalUID = errors.New("illegal uid") ErrInvalidCertificates = errors.New("certificates must be exactly two") + ErrInvalidSpanCarrier = errors.New("tracing: invalid span carrier") ErrKickingUsers = errors.New("failed to kick users, check array with failed uids") ErrMemberAlreadyExists = errors.New("member already exists in group") ErrMemberNotFound = errors.New("member not found in the group") diff --git a/vendor/github.com/topfreegames/pitaya/context/context.go b/vendor/github.com/topfreegames/pitaya/context/context.go index 777291d..372e136 100644 --- a/vendor/github.com/topfreegames/pitaya/context/context.go +++ b/vendor/github.com/topfreegames/pitaya/context/context.go @@ -34,7 +34,7 @@ func AddToPropagateCtx(ctx context.Context, key string, val interface{}) context return context.WithValue(ctx, constants.PropagateCtxKey, propagate) } -// GetFromPropagateCtx adds a key and value to the propagate +// GetFromPropagateCtx get a value from the propagate func GetFromPropagateCtx(ctx context.Context, key string) interface{} { propagate := ToMap(ctx) if val, ok := propagate[key]; ok { diff --git a/vendor/github.com/topfreegames/pitaya/push.go b/vendor/github.com/topfreegames/pitaya/push.go index c572e53..aa70dcf 100644 --- a/vendor/github.com/topfreegames/pitaya/push.go +++ b/vendor/github.com/topfreegames/pitaya/push.go @@ -59,7 +59,7 @@ func SendPushToUsers(route string, v interface{}, uids []string, frontendType st } if err = app.rpcClient.SendPush(uid, &cluster.Server{Type: frontendType}, push); err != nil { notPushedUids = append(notPushedUids, uid) - logger.Log.Errorf("RPCClient send message error, UID=%d, SvType=%s, Error=%s", uid, frontendType, err.Error()) + logger.Log.Errorf("RPCClient send message error, UID=%s, SvType=%s, Error=%s", uid, frontendType, err.Error()) } } else { notPushedUids = append(notPushedUids, uid) diff --git a/vendor/github.com/topfreegames/pitaya/tracing/span.go b/vendor/github.com/topfreegames/pitaya/tracing/span.go index 5530837..97ae4f8 100644 --- a/vendor/github.com/topfreegames/pitaya/tracing/span.go +++ b/vendor/github.com/topfreegames/pitaya/tracing/span.go @@ -21,15 +21,32 @@ package tracing import ( - "bytes" "context" - "encoding/base64" opentracing "github.com/opentracing/opentracing-go" "github.com/topfreegames/pitaya/constants" pcontext "github.com/topfreegames/pitaya/context" + "github.com/topfreegames/pitaya/logger" ) +func castValueToCarrier(val interface{}) (opentracing.TextMapCarrier, error) { + if v, ok := val.(opentracing.TextMapCarrier); ok { + return v, nil + } + if m, ok := val.(map[string]interface{}); ok { + carrier := map[string]string{} + for k, v := range m { + if s, ok := v.(string); ok { + carrier[k] = s + } else { + logger.Log.Warnf("value from span carrier cannot be cast to string: %+v", v) + } + } + return opentracing.TextMapCarrier(carrier), nil + } + return nil, constants.ErrInvalidSpanCarrier +} + // ExtractSpan retrieves an opentracing span context from the given context.Context // The span context can be received directly (inside the context) or via an RPC call // (encoded in binary format) @@ -38,18 +55,13 @@ func ExtractSpan(ctx context.Context) (opentracing.SpanContext, error) { span := opentracing.SpanFromContext(ctx) if span == nil { if s := pcontext.GetFromPropagateCtx(ctx, constants.SpanPropagateCtxKey); s != nil { - var data []byte var err error - if dataString, ok := s.(string); ok { - data, err = base64.StdEncoding.DecodeString(dataString) - if err != nil { - return nil, err - } - } else if sData, ok := s.([]byte); ok { - data = sData + carrier, err := castValueToCarrier(s) + if err != nil { + return nil, err } tracer := opentracing.GlobalTracer() - spanCtx, err = tracer.Extract(opentracing.Binary, bytes.NewBuffer(data)) + spanCtx, err = tracer.Extract(opentracing.TextMap, carrier) if err != nil { return nil, err } @@ -69,13 +81,13 @@ func InjectSpan(ctx context.Context) (context.Context, error) { if span == nil { return ctx, nil } - spanData := new(bytes.Buffer) + spanData := opentracing.TextMapCarrier{} tracer := opentracing.GlobalTracer() - err := tracer.Inject(span.Context(), opentracing.Binary, spanData) + err := tracer.Inject(span.Context(), opentracing.TextMap, spanData) if err != nil { return nil, err } - return pcontext.AddToPropagateCtx(ctx, constants.SpanPropagateCtxKey, spanData.Bytes()), nil + return pcontext.AddToPropagateCtx(ctx, constants.SpanPropagateCtxKey, spanData), nil } // StartSpan starts a new span with a given parent context, operation name, tags and diff --git a/vendor/github.com/topfreegames/viaproxy/.travis.yml b/vendor/github.com/topfreegames/viaproxy/.travis.yml deleted file mode 100644 index 67a8b76..0000000 --- a/vendor/github.com/topfreegames/viaproxy/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go - -go: - - 1.8 - - 1.9 - - tip - -script: go test -v . diff --git a/vendor/github.com/topfreegames/viaproxy/LICENSE b/vendor/github.com/topfreegames/viaproxy/LICENSE deleted file mode 100644 index 037093c..0000000 --- a/vendor/github.com/topfreegames/viaproxy/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Leandro López - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/topfreegames/viaproxy/README.md b/vendor/github.com/topfreegames/viaproxy/README.md deleted file mode 100644 index c27633f..0000000 --- a/vendor/github.com/topfreegames/viaproxy/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# Proxy Protocol support for Go net.Conn - -Regular Go `net` doesn't support [Proxy Protocol](http://www.haproxy.com/blog/haproxy/proxy-protocol/) when being load balanced with this option enabled. This makes you loose the original remote address and will report the load balancer's address instead on `net.Conn.RemoteAddr()`. This package adds allows you to create `net.Conn` objects that know how to understand Proxy Protocol. - -You can read more about this in my [Proxy Protocol: what is it and how to use it with Go](https://inkel.github.io/posts/proxy-protocol/) article. - -If you are not using a proxy-protocol, this wrapper will also work. - -## Usage -In your server, you can do the following: - -```go -ln, err := net.Listen("tcp", *addr) -if err != nil { - log.Fatal(err) -} - -for { - cn, err := ln.Accept() - if err != nil { - log.Println("ln.Accept():", err) - continue - } - - pcn, err := viaproxy.Wrap(cn) - if err != nil { - log.Println("Wrap():", err) - continue - } - - log.Printf("remote address is: %v", pcn.RemoteAddr()) - log.Printf("local address is: %v", pcn.LocalAddr()) - log.Printf("proxy address is: %v", pcn.ProxyAddr()) - pcn.Close() -} -``` - -Given that one can forget about this, you can also do the following: - -```go -ln, err := viaproxy.Listen("tcp", *addr) -if err != nil { - log.Fatal(err) -} - -for { - cn, err := ln.Accept() - if err != nil { - log.Println("ln.Accept():", err) - continue - } - - // The connection should be safe to be converted to a *viaproxy.Conn - // structure. - pcn := conn.(*viaproxy.Conn) - log.Printf("remote address is: %v", pcn.RemoteAddr()) - log.Printf("local address is: %v", pcn.LocalAddr()) - log.Printf("proxy address is: %v", pcn.ProxyAddr()) - pcn.Close() -} -``` - -In this case, `Accept` returns a generic [`net.Conn`](https://golang.org/pkg/net/#Conn) object. If you want to directly use a `Conn` object (which satisfies the `net.Conn` interface), you can use `AcceptFromProxy` instead: - -```go -ln, err := viaproxy.Listen("tcp", *addr) -if err != nil { - log.Fatal(err) -} - -for { - cn, err := ln.AcceptFromProxy() - if err != nil { - log.Println("ln.Accept():", err) - continue - } - - // The connection should be safe to be converted to a *viaproxy.Conn - // structure. - log.Printf("remote address is: %v", cn.RemoteAddr()) - log.Printf("local address is: %v", cn.LocalAddr()) - log.Printf("proxy address is: %v", cn.ProxyAddr()) - cn.Close() -} -``` - -## Caveats -* Only works with TCP connections. -* Both endpoints of the connection **must** be compatible with proxy protocol. - -## License -See [LICENSE](LICENSE). diff --git a/vendor/github.com/topfreegames/viaproxy/conn.go b/vendor/github.com/topfreegames/viaproxy/conn.go deleted file mode 100644 index 6a357db..0000000 --- a/vendor/github.com/topfreegames/viaproxy/conn.go +++ /dev/null @@ -1,179 +0,0 @@ -package viaproxy - -import ( - "bufio" - "bytes" - "fmt" - "io" - "net" - "strconv" - "time" -) - -// Wrap takes a net.Conn and returns a pointer to Conn that knows how to -// properly identify the remote address if it comes via a proxy that -// supports the Proxy Protocol. -func Wrap(cn net.Conn) (*Conn, error) { - c := &Conn{cn: cn, r: bufio.NewReader(cn)} - if err := c.parse(); err != nil { - return nil, err - } - return c, nil -} - -// Conn is an implementation of net.Conn interface for TCP connections that come -// from a proxy that users the Proxy Protocol to communicate with the upstream -// servers. -type Conn struct { - cn net.Conn - r *bufio.Reader - proxy net.Addr - remote net.Addr -} - -// ProxyAddr returns the proxy remote network address. -func (c *Conn) ProxyAddr() net.Addr { return c.proxy } - -// RemoteAddr returns the remote network address. -func (c *Conn) RemoteAddr() net.Addr { - if c.remote != nil { - return c.remote - } - return c.cn.RemoteAddr() -} - -// LocalAddr returns the local network address. -func (c *Conn) LocalAddr() net.Addr { return c.cn.LocalAddr() } - -// Read reads data from the connection. -func (c *Conn) Read(b []byte) (int, error) { return c.r.Read(b) } - -// Close closes the connection. -func (c *Conn) Close() error { return c.cn.Close() } - -// SetDeadline implements the Conn SetDeadline method. -func (c *Conn) SetDeadline(t time.Time) error { return c.cn.SetDeadline(t) } - -// SetReadDeadline implements the Conn SetReadDeadline method. -func (c *Conn) SetReadDeadline(t time.Time) error { return c.cn.SetReadDeadline(t) } - -// SetWriteDeadline implements the Conn SetWriteDeadline method. -func (c *Conn) SetWriteDeadline(t time.Time) error { return c.cn.SetWriteDeadline(t) } - -// Write implements the Conn Write method. -func (c *Conn) Write(b []byte) (int, error) { return c.cn.Write(b) } - -var ( - unknown = []byte("UNKNOWN\r\n") - proxy = []byte("PROXY ") -) - -func (c *Conn) parse() error { - buf, err := c.r.Peek(len(proxy)) - if err != nil { - if err == bufio.ErrBufferFull || err == io.EOF { - return nil - } - - return fmt.Errorf("parsing proxy protocol header on loop: %q", err) - } - - if !bytes.Equal(buf, proxy) { - return nil - } - - err = c.init() - return err -} - -func (c *Conn) init() error { - // PROXY - buf := make([]byte, 6) - n, err := c.r.Read(buf) - if err != nil { - return err - } - if !bytes.Equal(buf, []byte("PROXY ")) { - return fmt.Errorf("invalid proxy protocol header prefix: %q", buf[:n]) - } - - buf, err = c.r.Peek(len(unknown)) - if err != nil { - return fmt.Errorf("parsing proxy protocol header: %q", err) - } - if bytes.Equal(buf, unknown) { - _, err = c.r.Discard(len(unknown)) - return err - } - - // TCP4 || TCP6 - buf = make([]byte, 5) - // This line cannot return error as the buffer of the *bufio.Reader already contains at least five characters from the call to Peek above. - c.r.Read(buf) - if !bytes.Equal([]byte("TCP4 "), buf) && !bytes.Equal([]byte("TCP6 "), buf) { - return fmt.Errorf("unrecognized protocol: %q", buf) - } - - // CLIENT IP - clientIP, err := c.readIP() - if err != nil { - return fmt.Errorf("cannot parse client IP: %q", err) - } - - // PROXY IP - proxyIP, err := c.readIP() - if err != nil { - return fmt.Errorf("cannot parse proxy IP: %q", err) - } - - // CLIENT PORT - clientPort, err := c.readPort(' ') - if err != nil { - return fmt.Errorf("cannot parse client port: %q", err) - } - - // PROXY PORT - proxyPort, err := c.readPort('\r') - if err != nil { - return fmt.Errorf("cannot parse proxy port: %q", err) - } - - // Trailing - b, err := c.r.ReadByte() - if err != nil || b != '\n' { - return fmt.Errorf("invalid trailing: %q", err) - } - - c.remote = &net.TCPAddr{IP: clientIP, Port: clientPort} - c.proxy = &net.TCPAddr{IP: proxyIP, Port: proxyPort} - - return nil -} - -func (c *Conn) readIP() (net.IP, error) { - p, err := c.r.ReadString(' ') - if err != nil { - return nil, err - } - - ip := net.ParseIP(p[:len(p)-1]) - if ip == nil { - return nil, fmt.Errorf("cannot parse IP %q", p) - } - - return ip, nil -} - -func (c *Conn) readPort(delim byte) (int, error) { - p, err := c.r.ReadString(delim) - if err != nil { - return 0, err - } - - port, err := strconv.Atoi(p[:len(p)-1]) - if err != nil { - return 0, err - } - - return port, nil -} diff --git a/vendor/github.com/topfreegames/viaproxy/doc.go b/vendor/github.com/topfreegames/viaproxy/doc.go deleted file mode 100644 index a732643..0000000 --- a/vendor/github.com/topfreegames/viaproxy/doc.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Package viaproxy provides the ability to manage connections that properly understand the -Proxy Protocol defined by Willy Tarreau for HAProxy. - -Regular net.Conn structures will return the "wrong" RemoteAddr when used behind a proxy: -the remote address informed will be the one of the proxy, not the one from the client -initiating the connection to the proxy. This package adds a wrapper for regular net.Conn -that checks for the existence of the proxy protocol line and if present, return a net.Conn -that reports the customer address when calling RemoteAddr. This wrapped connection can be -casted to *viaproxy.Conn to add access to an additional ProxyAddr method that will return -the proxy's address. - -In order to use this extended connection type we can call Wrap on an existing connection: - - ln, err := net.Listen("tcp", *addr) - if err != nil { - log.Fatal(err) - } - - for { - cn, err := ln.Accept() - if err != nil { - log.Println("ln.Accept():", err) - continue - } - - pcn, err := viaproxy.Wrap(cn) - if err != nil { - log.Println("Wrap():", err) - continue - } - - log.Printf("remote address is: %v", pcn.RemoteAddr()) - log.Printf("local address is: %v", pcn.LocalAddr()) - log.Printf("proxy address is: %v", pcn.ProxyAddr()) - pcn.Close() - } - -Package viaproxy also provides a Listener struct that already returns viaproxy.Conn -connections when calling AcceptFromProxy: - - ln, err := viaproxy.Listen("tcp", *addr) - if err != nil { - log.Fatal(err) - } - - for { - cn, err := ln.AcceptFromProxy() - if err != nil { - log.Println("ln.Accept():", err) - continue - } - - log.Printf("remote address is: %v", cn.RemoteAddr()) - log.Printf("local address is: %v", cn.LocalAddr()) - log.Printf("proxy address is: %v", cn.ProxyAddr()) - cn.Close() - } - -The Accept method in the Listener struct returns a generic net.Conn -which can safely be casted to a viaproxy.Conn: - - ln, err := viaproxy.Listen("tcp", *addr) - if err != nil { - log.Fatal(err) - } - - for { - cn, err := ln.Accept() - if err != nil { - log.Println("ln.Accept():", err) - continue - } - - // The connection should be safe to be converted to a *viaproxy.Conn - // structure. - pcn := conn.(*viaproxy.Conn) - log.Printf("remote address is: %v", pcn.RemoteAddr()) - log.Printf("local address is: %v", pcn.LocalAddr()) - log.Printf("proxy address is: %v", pcn.ProxyAddr()) - pcn.Close() - } - -Using viaproxy.Conn objects whenever a net.Conn is expected should be -safe in all cases. If you encounter an issue please send a bug report -to https://github.com/topfreegames/viaproxy/issues -*/ -package viaproxy diff --git a/vendor/github.com/topfreegames/viaproxy/listen.go b/vendor/github.com/topfreegames/viaproxy/listen.go deleted file mode 100644 index 89c2e26..0000000 --- a/vendor/github.com/topfreegames/viaproxy/listen.go +++ /dev/null @@ -1,44 +0,0 @@ -package viaproxy - -import ( - "net" -) - -// Listen returns a net.Listener that will wrap Accept so it returns -// net.Conn that know how to work with Proxy Protocol. -func Listen(network, address string) (*Listener, error) { - ln, err := net.Listen(network, address) - if err != nil { - return nil, err - } - - return &Listener{ln}, nil -} - -// Listener is a wrap on net.Listener that returns wrapped Conn -// objects. -type Listener struct{ ln net.Listener } - -// Close stops listening on the TCP address. Already Accepted -// connections are not closed. -func (l *Listener) Close() error { return l.ln.Close() } - -// Addr returns the listener's network address, a *TCPAddr. The Addr -// returned is shared by all invocations of Addr, so do not modify it. -func (l *Listener) Addr() net.Addr { return l.ln.Addr() } - -// Accept implements the Accept method in the Listener interface; it -// waits for the next call and returns a generic Conn. -func (l *Listener) Accept() (net.Conn, error) { - return l.AcceptFromProxy() -} - -// AcceptFromProxy accepts the next incoming call and returns the new -// connection. -func (l *Listener) AcceptFromProxy() (*Conn, error) { - cn, err := l.ln.Accept() - if err != nil { - return nil, err - } - return Wrap(cn) -}