cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2019.8.3

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

connection/connection.go

81lines · modecode

1package connection
2
3import (
4 "context"
5 "net"
6 "time"
7
8 "github.com/cloudflare/cloudflared/h2mux"
9 "github.com/cloudflare/cloudflared/tunnelrpc"
10 "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
11 tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
12 "github.com/google/uuid"
13 "github.com/pkg/errors"
14 "github.com/sirupsen/logrus"
15
16 rpc "zombiezen.com/go/capnproto2/rpc"
17)
18
19const (
20 openStreamTimeout = 30 * time.Second
21)
22
23type dialError struct {
24 cause error
25}
26
27func (e dialError) Error() string {
28 return e.cause.Error()
29}
30
31type Connection struct {
32 id uuid.UUID
33 muxer *h2mux.Muxer
34}
35
36func newConnection(muxer *h2mux.Muxer, edgeIP *net.TCPAddr) (*Connection, error) {
37 id, err := uuid.NewRandom()
38 if err != nil {
39 return nil, err
40 }
41 return &Connection{
42 id: id,
43 muxer: muxer,
44 }, nil
45}
46
47func (c *Connection) Serve(ctx context.Context) error {
48 // Serve doesn't return until h2mux is shutdown
49 return c.muxer.Serve(ctx)
50}
51
52// Connect is used to establish connections with cloudflare's edge network
53func (c *Connection) Connect(ctx context.Context, parameters *tunnelpogs.ConnectParameters, logger *logrus.Entry) (*pogs.ConnectResult, error) {
54 openStreamCtx, cancel := context.WithTimeout(ctx, openStreamTimeout)
55 defer cancel()
56
57 rpcConn, err := c.newRPConn(openStreamCtx, logger)
58 if err != nil {
59 return nil, errors.Wrap(err, "cannot create new RPC connection")
60 }
61 defer rpcConn.Close()
62
63 tsClient := tunnelpogs.TunnelServer_PogsClient{Client: rpcConn.Bootstrap(ctx)}
64
65 return tsClient.Connect(ctx, parameters)
66}
67
68func (c *Connection) Shutdown() {
69 c.muxer.Shutdown()
70}
71
72func (c *Connection) newRPConn(ctx context.Context, logger *logrus.Entry) (*rpc.Conn, error) {
73 stream, err := c.muxer.OpenRPCStream(ctx)
74 if err != nil {
75 return nil, err
76 }
77 return rpc.NewConn(
78 tunnelrpc.NewTransportLogger(logger.WithField("rpc", "connect"), rpc.StreamTransport(stream)),
79 tunnelrpc.ConnLog(logger.WithField("rpc", "connect")),
80 ), nil
81}
82