cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
connection/rpc.go
49lines · modeblame
bbf31377Nick Vollmar6 years ago | 1 | package connection |
| 2 | | |
| 3 | import ( | |
| 4 | "context" | |
| 5 | "fmt" | |
| 6 | "time" | |
| 7 | | |
| 8 | rpc "zombiezen.com/go/capnproto2/rpc" | |
| 9 | | |
| 10 | "github.com/cloudflare/cloudflared/h2mux" | |
046be632Dalton6 years ago | 11 | "github.com/cloudflare/cloudflared/logger" |
bbf31377Nick Vollmar6 years ago | 12 | "github.com/cloudflare/cloudflared/tunnelrpc" |
| 13 | tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs" | |
| 14 | ) | |
| 15 | | |
| 16 | // NewRPCClient creates and returns a new RPC client, which will communicate | |
| 17 | // using a stream on the given muxer | |
| 18 | func NewRPCClient( | |
| 19 | ctx context.Context, | |
| 20 | muxer *h2mux.Muxer, | |
046be632Dalton6 years ago | 21 | logger logger.Service, |
bbf31377Nick Vollmar6 years ago | 22 | openStreamTimeout time.Duration, |
| 23 | ) (client tunnelpogs.TunnelServer_PogsClient, err error) { | |
| 24 | openStreamCtx, openStreamCancel := context.WithTimeout(ctx, openStreamTimeout) | |
| 25 | defer openStreamCancel() | |
| 26 | stream, err := muxer.OpenRPCStream(openStreamCtx) | |
| 27 | if err != nil { | |
| 28 | return | |
| 29 | } | |
| 30 | | |
| 31 | if !isRPCStreamResponse(stream.Headers) { | |
| 32 | stream.Close() | |
| 33 | err = fmt.Errorf("rpc: bad response headers: %v", stream.Headers) | |
| 34 | return | |
| 35 | } | |
| 36 | | |
| 37 | conn := rpc.NewConn( | |
| 38 | tunnelrpc.NewTransportLogger(logger, rpc.StreamTransport(stream)), | |
| 39 | tunnelrpc.ConnLog(logger), | |
| 40 | ) | |
| 41 | client = tunnelpogs.TunnelServer_PogsClient{Client: conn.Bootstrap(ctx), Conn: conn} | |
| 42 | return client, nil | |
| 43 | } | |
| 44 | | |
| 45 | func isRPCStreamResponse(headers []h2mux.Header) bool { | |
| 46 | return len(headers) == 1 && | |
| 47 | headers[0].Name == ":status" && | |
| 48 | headers[0].Value == "200" | |
| 49 | } |