cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
carrier/carrier.go
161lines · modecode
| 1 | //Package carrier provides a WebSocket proxy to carry or proxy a connection |
| 2 | //from the local client to the edge. See it as a wrapper around any protocol |
| 3 | //that it packages up in a WebSocket connection to the edge. |
| 4 | package carrier |
| 5 | |
| 6 | import ( |
| 7 | "crypto/tls" |
| 8 | "io" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "strings" |
| 13 | |
| 14 | "github.com/cloudflare/cloudflared/h2mux" |
| 15 | "github.com/cloudflare/cloudflared/token" |
| 16 | |
| 17 | "github.com/pkg/errors" |
| 18 | "github.com/rs/zerolog" |
| 19 | ) |
| 20 | |
| 21 | const LogFieldOriginURL = "originURL" |
| 22 | |
| 23 | type StartOptions struct { |
| 24 | AppInfo *token.AppInfo |
| 25 | OriginURL string |
| 26 | Headers http.Header |
| 27 | Host string |
| 28 | TLSClientConfig *tls.Config |
| 29 | } |
| 30 | |
| 31 | // Connection wraps up all the needed functions to forward over the tunnel |
| 32 | type Connection interface { |
| 33 | // ServeStream is used to forward data from the client to the edge |
| 34 | ServeStream(*StartOptions, io.ReadWriter) error |
| 35 | |
| 36 | // StartServer is used to listen for incoming connections from the edge to the origin |
| 37 | StartServer(net.Listener, string, <-chan struct{}) error |
| 38 | } |
| 39 | |
| 40 | // StdinoutStream is empty struct for wrapping stdin/stdout |
| 41 | // into a single ReadWriter |
| 42 | type StdinoutStream struct { |
| 43 | } |
| 44 | |
| 45 | // Read will read from Stdin |
| 46 | func (c *StdinoutStream) Read(p []byte) (int, error) { |
| 47 | return os.Stdin.Read(p) |
| 48 | |
| 49 | } |
| 50 | |
| 51 | // Write will write to Stdout |
| 52 | func (c *StdinoutStream) Write(p []byte) (int, error) { |
| 53 | return os.Stdout.Write(p) |
| 54 | } |
| 55 | |
| 56 | // Helper to allow defering the response close with a check that the resp is not nil |
| 57 | func closeRespBody(resp *http.Response) { |
| 58 | if resp != nil { |
| 59 | _ = resp.Body.Close() |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // StartForwarder will setup a listener on a specified address/port and then |
| 64 | // forward connections to the origin by calling `Serve()`. |
| 65 | func StartForwarder(conn Connection, address string, shutdownC <-chan struct{}, options *StartOptions) error { |
| 66 | listener, err := net.Listen("tcp", address) |
| 67 | if err != nil { |
| 68 | return errors.Wrap(err, "failed to start forwarding server") |
| 69 | } |
| 70 | return Serve(conn, listener, shutdownC, options) |
| 71 | } |
| 72 | |
| 73 | // StartClient will copy the data from stdin/stdout over a WebSocket connection |
| 74 | // to the edge (originURL) |
| 75 | func StartClient(conn Connection, stream io.ReadWriter, options *StartOptions) error { |
| 76 | return conn.ServeStream(options, stream) |
| 77 | } |
| 78 | |
| 79 | // Serve accepts incoming connections on the specified net.Listener. |
| 80 | // Each connection is handled in a new goroutine: its data is copied over a |
| 81 | // WebSocket connection to the edge (originURL). |
| 82 | // `Serve` always closes `listener`. |
| 83 | func Serve(remoteConn Connection, listener net.Listener, shutdownC <-chan struct{}, options *StartOptions) error { |
| 84 | defer listener.Close() |
| 85 | errChan := make(chan error) |
| 86 | |
| 87 | go func() { |
| 88 | for { |
| 89 | conn, err := listener.Accept() |
| 90 | if err != nil { |
| 91 | // don't block if parent goroutine quit early |
| 92 | select { |
| 93 | case errChan <- err: |
| 94 | default: |
| 95 | } |
| 96 | return |
| 97 | } |
| 98 | go serveConnection(remoteConn, conn, options) |
| 99 | } |
| 100 | }() |
| 101 | |
| 102 | select { |
| 103 | case <-shutdownC: |
| 104 | return nil |
| 105 | case err := <-errChan: |
| 106 | return err |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // serveConnection handles connections for the Serve() call |
| 111 | func serveConnection(remoteConn Connection, c net.Conn, options *StartOptions) { |
| 112 | defer c.Close() |
| 113 | _ = remoteConn.ServeStream(options, c) |
| 114 | } |
| 115 | |
| 116 | // IsAccessResponse checks the http Response to see if the url location |
| 117 | // contains the Access structure. |
| 118 | func IsAccessResponse(resp *http.Response) bool { |
| 119 | if resp == nil || resp.StatusCode != http.StatusFound { |
| 120 | return false |
| 121 | } |
| 122 | |
| 123 | location, err := resp.Location() |
| 124 | if err != nil || location == nil { |
| 125 | return false |
| 126 | } |
| 127 | if strings.HasPrefix(location.Path, token.AccessLoginWorkerPath) { |
| 128 | return true |
| 129 | } |
| 130 | |
| 131 | return false |
| 132 | } |
| 133 | |
| 134 | // BuildAccessRequest builds an HTTP request with the Access token set |
| 135 | func BuildAccessRequest(options *StartOptions, log *zerolog.Logger) (*http.Request, error) { |
| 136 | req, err := http.NewRequest(http.MethodGet, options.OriginURL, nil) |
| 137 | if err != nil { |
| 138 | return nil, err |
| 139 | } |
| 140 | |
| 141 | token, err := token.FetchTokenWithRedirect(req.URL, options.AppInfo, log) |
| 142 | if err != nil { |
| 143 | return nil, err |
| 144 | } |
| 145 | |
| 146 | // We need to create a new request as FetchToken will modify req (boo mutable) |
| 147 | // as it has to follow redirect on the API and such, so here we init a new one |
| 148 | originRequest, err := http.NewRequest(http.MethodGet, options.OriginURL, nil) |
| 149 | if err != nil { |
| 150 | return nil, err |
| 151 | } |
| 152 | originRequest.Header.Set(h2mux.CFAccessTokenHeader, token) |
| 153 | |
| 154 | for k, v := range options.Headers { |
| 155 | if len(v) >= 1 { |
| 156 | originRequest.Header.Set(k, v[0]) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | return originRequest, nil |
| 161 | } |