cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
carrier/carrier.go
216lines · 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 | "io" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "strings" |
| 12 | |
| 13 | "github.com/cloudflare/cloudflared/cmd/cloudflared/token" |
| 14 | cloudflaredWebsocket "github.com/cloudflare/cloudflared/websocket" |
| 15 | "github.com/gorilla/websocket" |
| 16 | "github.com/sirupsen/logrus" |
| 17 | ) |
| 18 | |
| 19 | type StartOptions struct { |
| 20 | OriginURL string |
| 21 | Headers http.Header |
| 22 | } |
| 23 | |
| 24 | // StdinoutStream is empty struct for wrapping stdin/stdout |
| 25 | // into a single ReadWriter |
| 26 | type StdinoutStream struct { |
| 27 | } |
| 28 | |
| 29 | // Read will read from Stdin |
| 30 | func (c *StdinoutStream) Read(p []byte) (int, error) { |
| 31 | return os.Stdin.Read(p) |
| 32 | |
| 33 | } |
| 34 | |
| 35 | // Write will write to Stdout |
| 36 | func (c *StdinoutStream) Write(p []byte) (int, error) { |
| 37 | return os.Stdout.Write(p) |
| 38 | } |
| 39 | |
| 40 | // Helper to allow defering the response close with a check that the resp is not nil |
| 41 | func closeRespBody(resp *http.Response) { |
| 42 | if resp != nil { |
| 43 | resp.Body.Close() |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // StartClient will copy the data from stdin/stdout over a WebSocket connection |
| 48 | // to the edge (originURL) |
| 49 | func StartClient(logger *logrus.Logger, stream io.ReadWriter, options *StartOptions) error { |
| 50 | return serveStream(logger, stream, options) |
| 51 | } |
| 52 | |
| 53 | // StartServer will setup a listener on a specified address/port and then |
| 54 | // forward connections to the origin by calling `Serve()`. |
| 55 | func StartServer(logger *logrus.Logger, address string, shutdownC <-chan struct{}, options *StartOptions) error { |
| 56 | listener, err := net.Listen("tcp", address) |
| 57 | if err != nil { |
| 58 | logger.WithError(err).Error("failed to start forwarding server") |
| 59 | return err |
| 60 | } |
| 61 | logger.Info("Started listening on ", address) |
| 62 | return Serve(logger, listener, shutdownC, options) |
| 63 | } |
| 64 | |
| 65 | // Serve accepts incoming connections on the specified net.Listener. |
| 66 | // Each connection is handled in a new goroutine: its data is copied over a |
| 67 | // WebSocket connection to the edge (originURL). |
| 68 | // `Serve` always closes `listener`. |
| 69 | func Serve(logger *logrus.Logger, listener net.Listener, shutdownC <-chan struct{}, options *StartOptions) error { |
| 70 | defer listener.Close() |
| 71 | for { |
| 72 | select { |
| 73 | case <-shutdownC: |
| 74 | return nil |
| 75 | default: |
| 76 | conn, err := listener.Accept() |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | go serveConnection(logger, conn, options) |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | // serveConnection handles connections for the Serve() call |
| 86 | func serveConnection(logger *logrus.Logger, c net.Conn, options *StartOptions) { |
| 87 | defer c.Close() |
| 88 | serveStream(logger, c, options) |
| 89 | } |
| 90 | |
| 91 | // serveStream will serve the data over the WebSocket stream |
| 92 | func serveStream(logger *logrus.Logger, conn io.ReadWriter, options *StartOptions) error { |
| 93 | wsConn, err := createWebsocketStream(options) |
| 94 | if err != nil { |
| 95 | logger.WithError(err).Errorf("failed to connect to %s\n", options.OriginURL) |
| 96 | return err |
| 97 | } |
| 98 | defer wsConn.Close() |
| 99 | |
| 100 | cloudflaredWebsocket.Stream(wsConn, conn) |
| 101 | |
| 102 | return nil |
| 103 | } |
| 104 | |
| 105 | // createWebsocketStream will create a WebSocket connection to stream data over |
| 106 | // It also handles redirects from Access and will present that flow if |
| 107 | // the token is not present on the request |
| 108 | func createWebsocketStream(options *StartOptions) (*cloudflaredWebsocket.Conn, error) { |
| 109 | req, err := http.NewRequest(http.MethodGet, options.OriginURL, nil) |
| 110 | if err != nil { |
| 111 | return nil, err |
| 112 | } |
| 113 | req.Header = options.Headers |
| 114 | |
| 115 | wsConn, resp, err := cloudflaredWebsocket.ClientConnect(req, nil) |
| 116 | defer closeRespBody(resp) |
| 117 | if err != nil && IsAccessResponse(resp) { |
| 118 | wsConn, err = createAccessAuthenticatedStream(options) |
| 119 | if err != nil { |
| 120 | return nil, err |
| 121 | } |
| 122 | } else if err != nil { |
| 123 | return nil, err |
| 124 | } |
| 125 | |
| 126 | return &cloudflaredWebsocket.Conn{Conn: wsConn}, nil |
| 127 | } |
| 128 | |
| 129 | // IsAccessResponse checks the http Response to see if the url location |
| 130 | // contains the Access structure. |
| 131 | func IsAccessResponse(resp *http.Response) bool { |
| 132 | if resp == nil || resp.StatusCode != http.StatusFound { |
| 133 | return false |
| 134 | } |
| 135 | |
| 136 | location, err := resp.Location() |
| 137 | if err != nil || location == nil { |
| 138 | return false |
| 139 | } |
| 140 | if strings.HasPrefix(location.Path, "/cdn-cgi/access/login") { |
| 141 | return true |
| 142 | } |
| 143 | |
| 144 | return false |
| 145 | } |
| 146 | |
| 147 | // createAccessAuthenticatedStream will try load a token from storage and make |
| 148 | // a connection with the token set on the request. If it still get redirect, |
| 149 | // this probably means the token in storage is invalid (expired/revoked). If that |
| 150 | // happens it deletes the token and runs the connection again, so the user can |
| 151 | // login again and generate a new one. |
| 152 | func createAccessAuthenticatedStream(options *StartOptions) (*websocket.Conn, error) { |
| 153 | wsConn, resp, err := createAccessWebSocketStream(options) |
| 154 | defer closeRespBody(resp) |
| 155 | if err == nil { |
| 156 | return wsConn, nil |
| 157 | } |
| 158 | |
| 159 | if !IsAccessResponse(resp) { |
| 160 | return nil, err |
| 161 | } |
| 162 | |
| 163 | // Access Token is invalid for some reason. Go through regen flow |
| 164 | originReq, err := http.NewRequest(http.MethodGet, options.OriginURL, nil) |
| 165 | if err != nil { |
| 166 | return nil, err |
| 167 | } |
| 168 | if err := token.RemoveTokenIfExists(originReq.URL); err != nil { |
| 169 | return nil, err |
| 170 | } |
| 171 | wsConn, resp, err = createAccessWebSocketStream(options) |
| 172 | defer closeRespBody(resp) |
| 173 | if err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | |
| 177 | return wsConn, nil |
| 178 | } |
| 179 | |
| 180 | // createAccessWebSocketStream builds an Access request and makes a connection |
| 181 | func createAccessWebSocketStream(options *StartOptions) (*websocket.Conn, *http.Response, error) { |
| 182 | req, err := BuildAccessRequest(options) |
| 183 | if err != nil { |
| 184 | return nil, nil, err |
| 185 | } |
| 186 | return cloudflaredWebsocket.ClientConnect(req, nil) |
| 187 | } |
| 188 | |
| 189 | // buildAccessRequest builds an HTTP request with the Access token set |
| 190 | func BuildAccessRequest(options *StartOptions) (*http.Request, error) { |
| 191 | req, err := http.NewRequest(http.MethodGet, options.OriginURL, nil) |
| 192 | if err != nil { |
| 193 | return nil, err |
| 194 | } |
| 195 | |
| 196 | token, err := token.FetchToken(req.URL) |
| 197 | if err != nil { |
| 198 | return nil, err |
| 199 | } |
| 200 | |
| 201 | // We need to create a new request as FetchToken will modify req (boo mutable) |
| 202 | // as it has to follow redirect on the API and such, so here we init a new one |
| 203 | originRequest, err := http.NewRequest(http.MethodGet, options.OriginURL, nil) |
| 204 | if err != nil { |
| 205 | return nil, err |
| 206 | } |
| 207 | originRequest.Header.Set("cf-access-token", token) |
| 208 | |
| 209 | for k, v := range options.Headers { |
| 210 | if len(v) >= 1 { |
| 211 | originRequest.Header.Set(k, v[0]) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | return originRequest, nil |
| 216 | } |
| 217 | |