cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
origin/tunnel.go
691lines · modecode
| 1 | package origin |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "crypto/tls" |
| 6 | "fmt" |
| 7 | "github.com/google/uuid" |
| 8 | "io" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | "golang.org/x/net/context" |
| 17 | "golang.org/x/sync/errgroup" |
| 18 | |
| 19 | "github.com/cloudflare/cloudflared/h2mux" |
| 20 | "github.com/cloudflare/cloudflared/tunnelrpc" |
| 21 | tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs" |
| 22 | "github.com/cloudflare/cloudflared/validation" |
| 23 | "github.com/cloudflare/cloudflared/websocket" |
| 24 | |
| 25 | raven "github.com/getsentry/raven-go" |
| 26 | "github.com/pkg/errors" |
| 27 | _ "github.com/prometheus/client_golang/prometheus" |
| 28 | log "github.com/sirupsen/logrus" |
| 29 | rpc "zombiezen.com/go/capnproto2/rpc" |
| 30 | ) |
| 31 | |
| 32 | const ( |
| 33 | dialTimeout = 15 * time.Second |
| 34 | lbProbeUserAgentPrefix = "Mozilla/5.0 (compatible; Cloudflare-Traffic-Manager/1.0; +https://www.cloudflare.com/traffic-manager/;" |
| 35 | TagHeaderNamePrefix = "Cf-Warp-Tag-" |
| 36 | DuplicateConnectionError = "EDUPCONN" |
| 37 | ) |
| 38 | |
| 39 | type TunnelConfig struct { |
| 40 | EdgeAddrs []string |
| 41 | OriginUrl string |
| 42 | Hostname string |
| 43 | OriginCert []byte |
| 44 | TlsConfig *tls.Config |
| 45 | ClientTlsConfig *tls.Config |
| 46 | Retries uint |
| 47 | HeartbeatInterval time.Duration |
| 48 | MaxHeartbeats uint64 |
| 49 | ClientID string |
| 50 | BuildInfo *BuildInfo |
| 51 | ReportedVersion string |
| 52 | LBPool string |
| 53 | Tags []tunnelpogs.Tag |
| 54 | HAConnections int |
| 55 | HTTPTransport http.RoundTripper |
| 56 | Metrics *TunnelMetrics |
| 57 | MetricsUpdateFreq time.Duration |
| 58 | ProtocolLogger *log.Logger |
| 59 | Logger *log.Logger |
| 60 | IsAutoupdated bool |
| 61 | GracePeriod time.Duration |
| 62 | RunFromTerminal bool |
| 63 | NoChunkedEncoding bool |
| 64 | WSGI bool |
| 65 | CompressionQuality uint64 |
| 66 | } |
| 67 | |
| 68 | type dialError struct { |
| 69 | cause error |
| 70 | } |
| 71 | |
| 72 | func (e dialError) Error() string { |
| 73 | return e.cause.Error() |
| 74 | } |
| 75 | |
| 76 | type dupConnRegisterTunnelError struct{} |
| 77 | |
| 78 | func (e dupConnRegisterTunnelError) Error() string { |
| 79 | return "already connected to this server" |
| 80 | } |
| 81 | |
| 82 | type muxerShutdownError struct{} |
| 83 | |
| 84 | func (e muxerShutdownError) Error() string { |
| 85 | return "muxer shutdown" |
| 86 | } |
| 87 | |
| 88 | // RegisterTunnel error from server |
| 89 | type serverRegisterTunnelError struct { |
| 90 | cause error |
| 91 | permanent bool |
| 92 | } |
| 93 | |
| 94 | func (e serverRegisterTunnelError) Error() string { |
| 95 | return e.cause.Error() |
| 96 | } |
| 97 | |
| 98 | // RegisterTunnel error from client |
| 99 | type clientRegisterTunnelError struct { |
| 100 | cause error |
| 101 | } |
| 102 | |
| 103 | func (e clientRegisterTunnelError) Error() string { |
| 104 | return e.cause.Error() |
| 105 | } |
| 106 | |
| 107 | func (c *TunnelConfig) RegistrationOptions(connectionID uint8, OriginLocalIP string, uuid uuid.UUID) *tunnelpogs.RegistrationOptions { |
| 108 | policy := tunnelrpc.ExistingTunnelPolicy_balance |
| 109 | if c.HAConnections <= 1 && c.LBPool == "" { |
| 110 | policy = tunnelrpc.ExistingTunnelPolicy_disconnect |
| 111 | } |
| 112 | return &tunnelpogs.RegistrationOptions{ |
| 113 | ClientID: c.ClientID, |
| 114 | Version: c.ReportedVersion, |
| 115 | OS: fmt.Sprintf("%s_%s", c.BuildInfo.GoOS, c.BuildInfo.GoArch), |
| 116 | ExistingTunnelPolicy: policy, |
| 117 | PoolName: c.LBPool, |
| 118 | Tags: c.Tags, |
| 119 | ConnectionID: connectionID, |
| 120 | OriginLocalIP: OriginLocalIP, |
| 121 | IsAutoupdated: c.IsAutoupdated, |
| 122 | RunFromTerminal: c.RunFromTerminal, |
| 123 | CompressionQuality: c.CompressionQuality, |
| 124 | UUID: uuid.String(), |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func StartTunnelDaemon(config *TunnelConfig, shutdownC <-chan struct{}, connectedSignal chan struct{}) error { |
| 129 | ctx, cancel := context.WithCancel(context.Background()) |
| 130 | go func() { |
| 131 | <-shutdownC |
| 132 | cancel() |
| 133 | }() |
| 134 | // If a user specified negative HAConnections, we will treat it as requesting 1 connection |
| 135 | if config.HAConnections > 1 { |
| 136 | return NewSupervisor(config).Run(ctx, connectedSignal) |
| 137 | } else { |
| 138 | addrs, err := ResolveEdgeIPs(config.EdgeAddrs) |
| 139 | if err != nil { |
| 140 | return err |
| 141 | } |
| 142 | return ServeTunnelLoop(ctx, config, addrs[0], 0, connectedSignal) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | func ServeTunnelLoop(ctx context.Context, |
| 147 | config *TunnelConfig, |
| 148 | addr *net.TCPAddr, |
| 149 | connectionID uint8, |
| 150 | connectedSignal chan struct{}, |
| 151 | ) error { |
| 152 | logger := config.Logger |
| 153 | config.Metrics.incrementHaConnections() |
| 154 | defer config.Metrics.decrementHaConnections() |
| 155 | backoff := BackoffHandler{MaxRetries: config.Retries} |
| 156 | // Used to close connectedSignal no more than once |
| 157 | connectedFuse := h2mux.NewBooleanFuse() |
| 158 | go func() { |
| 159 | if connectedFuse.Await() { |
| 160 | close(connectedSignal) |
| 161 | } |
| 162 | }() |
| 163 | // Ensure the above goroutine will terminate if we return without connecting |
| 164 | defer connectedFuse.Fuse(false) |
| 165 | for { |
| 166 | err, recoverable := ServeTunnel(ctx, config, addr, connectionID, connectedFuse, &backoff) |
| 167 | if recoverable { |
| 168 | if duration, ok := backoff.GetBackoffDuration(ctx); ok { |
| 169 | logger.Infof("Retrying in %s seconds", duration) |
| 170 | backoff.Backoff(ctx) |
| 171 | continue |
| 172 | } |
| 173 | } |
| 174 | return err |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | func ServeTunnel( |
| 179 | ctx context.Context, |
| 180 | config *TunnelConfig, |
| 181 | addr *net.TCPAddr, |
| 182 | connectionID uint8, |
| 183 | connectedFuse *h2mux.BooleanFuse, |
| 184 | backoff *BackoffHandler, |
| 185 | ) (err error, recoverable bool) { |
| 186 | // Treat panics as recoverable errors |
| 187 | defer func() { |
| 188 | if r := recover(); r != nil { |
| 189 | var ok bool |
| 190 | err, ok = r.(error) |
| 191 | if !ok { |
| 192 | err = fmt.Errorf("ServeTunnel: %v", r) |
| 193 | } |
| 194 | recoverable = true |
| 195 | } |
| 196 | }() |
| 197 | |
| 198 | connectionTag := uint8ToString(connectionID) |
| 199 | logger := config.Logger.WithField("connectionID", connectionTag) |
| 200 | |
| 201 | // additional tags to send other than hostname which is set in cloudflared main package |
| 202 | tags := make(map[string]string) |
| 203 | tags["ha"] = connectionTag |
| 204 | |
| 205 | // Returns error from parsing the origin URL or handshake errors |
| 206 | handler, originLocalIP, err := NewTunnelHandler(ctx, config, addr.String(), connectionID) |
| 207 | if err != nil { |
| 208 | errLog := config.Logger.WithError(err) |
| 209 | switch err.(type) { |
| 210 | case dialError: |
| 211 | errLog.Error("Unable to dial edge") |
| 212 | case h2mux.MuxerHandshakeError: |
| 213 | errLog.Error("Handshake failed with edge server") |
| 214 | default: |
| 215 | errLog.Error("Tunnel creation failure") |
| 216 | return err, false |
| 217 | } |
| 218 | return err, true |
| 219 | } |
| 220 | |
| 221 | errGroup, serveCtx := errgroup.WithContext(ctx) |
| 222 | |
| 223 | errGroup.Go(func() error { |
| 224 | err := RegisterTunnel(serveCtx, handler.muxer, config, connectionID, originLocalIP) |
| 225 | if err == nil { |
| 226 | connectedFuse.Fuse(true) |
| 227 | backoff.SetGracePeriod() |
| 228 | } |
| 229 | return err |
| 230 | }) |
| 231 | |
| 232 | errGroup.Go(func() error { |
| 233 | updateMetricsTickC := time.Tick(config.MetricsUpdateFreq) |
| 234 | for { |
| 235 | select { |
| 236 | case <-serveCtx.Done(): |
| 237 | // UnregisterTunnel blocks until the RPC call returns |
| 238 | err := UnregisterTunnel(handler.muxer, config.GracePeriod, config.Logger) |
| 239 | handler.muxer.Shutdown() |
| 240 | return err |
| 241 | case <-updateMetricsTickC: |
| 242 | handler.UpdateMetrics(connectionTag) |
| 243 | } |
| 244 | } |
| 245 | }) |
| 246 | |
| 247 | errGroup.Go(func() error { |
| 248 | // All routines should stop when muxer finish serving. When muxer is shutdown |
| 249 | // gracefully, it doesn't return an error, so we need to return errMuxerShutdown |
| 250 | // here to notify other routines to stop |
| 251 | err := handler.muxer.Serve(serveCtx) |
| 252 | if err == nil { |
| 253 | return muxerShutdownError{} |
| 254 | } |
| 255 | return err |
| 256 | }) |
| 257 | |
| 258 | err = errGroup.Wait() |
| 259 | if err != nil { |
| 260 | switch castedErr := err.(type) { |
| 261 | case dupConnRegisterTunnelError: |
| 262 | logger.Info("Already connected to this server, selecting a different one") |
| 263 | return err, true |
| 264 | case serverRegisterTunnelError: |
| 265 | logger.WithError(castedErr.cause).Error("Register tunnel error from server side") |
| 266 | // Don't send registration error return from server to Sentry. They are |
| 267 | // logged on server side |
| 268 | return castedErr.cause, !castedErr.permanent |
| 269 | case clientRegisterTunnelError: |
| 270 | logger.WithError(castedErr.cause).Error("Register tunnel error on client side") |
| 271 | raven.CaptureError(castedErr.cause, tags) |
| 272 | return err, true |
| 273 | case muxerShutdownError: |
| 274 | logger.Infof("Muxer shutdown") |
| 275 | return err, true |
| 276 | default: |
| 277 | logger.WithError(err).Error("Serve tunnel error") |
| 278 | raven.CaptureError(err, tags) |
| 279 | return err, true |
| 280 | } |
| 281 | } |
| 282 | return nil, true |
| 283 | } |
| 284 | |
| 285 | func IsRPCStreamResponse(headers []h2mux.Header) bool { |
| 286 | if len(headers) != 1 { |
| 287 | return false |
| 288 | } |
| 289 | if headers[0].Name != ":status" || headers[0].Value != "200" { |
| 290 | return false |
| 291 | } |
| 292 | return true |
| 293 | } |
| 294 | |
| 295 | func RegisterTunnel(ctx context.Context, muxer *h2mux.Muxer, config *TunnelConfig, connectionID uint8, originLocalIP string) error { |
| 296 | config.Logger.Debug("initiating RPC stream to register") |
| 297 | stream, err := muxer.OpenStream([]h2mux.Header{ |
| 298 | {Name: ":method", Value: "RPC"}, |
| 299 | {Name: ":scheme", Value: "capnp"}, |
| 300 | {Name: ":path", Value: "*"}, |
| 301 | }, nil) |
| 302 | if err != nil { |
| 303 | // RPC stream open error |
| 304 | return clientRegisterTunnelError{cause: err} |
| 305 | } |
| 306 | if !IsRPCStreamResponse(stream.Headers) { |
| 307 | // stream response error |
| 308 | return clientRegisterTunnelError{cause: err} |
| 309 | } |
| 310 | conn := rpc.NewConn( |
| 311 | tunnelrpc.NewTransportLogger(config.Logger.WithField("subsystem", "rpc-register"), rpc.StreamTransport(stream)), |
| 312 | tunnelrpc.ConnLog(config.Logger.WithField("subsystem", "rpc-transport")), |
| 313 | ) |
| 314 | defer conn.Close() |
| 315 | ts := tunnelpogs.TunnelServer_PogsClient{Client: conn.Bootstrap(ctx)} |
| 316 | // Request server info without blocking tunnel registration; must use capnp library directly. |
| 317 | tsClient := tunnelrpc.TunnelServer{Client: ts.Client} |
| 318 | serverInfoPromise := tsClient.GetServerInfo(ctx, func(tunnelrpc.TunnelServer_getServerInfo_Params) error { |
| 319 | return nil |
| 320 | }) |
| 321 | uuid, err := uuid.NewRandom() |
| 322 | if err != nil { |
| 323 | return clientRegisterTunnelError{cause: err} |
| 324 | } |
| 325 | registration, err := ts.RegisterTunnel( |
| 326 | ctx, |
| 327 | config.OriginCert, |
| 328 | config.Hostname, |
| 329 | config.RegistrationOptions(connectionID, originLocalIP, uuid), |
| 330 | ) |
| 331 | LogServerInfo(serverInfoPromise.Result(), connectionID, config.Metrics, config.Logger) |
| 332 | if err != nil { |
| 333 | // RegisterTunnel RPC failure |
| 334 | return clientRegisterTunnelError{cause: err} |
| 335 | } |
| 336 | for _, logLine := range registration.LogLines { |
| 337 | config.Logger.Info(logLine) |
| 338 | } |
| 339 | if registration.Err == DuplicateConnectionError { |
| 340 | return dupConnRegisterTunnelError{} |
| 341 | } else if registration.Err != "" { |
| 342 | return serverRegisterTunnelError{ |
| 343 | cause: fmt.Errorf("Server error: %s", registration.Err), |
| 344 | permanent: registration.PermanentFailure, |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | if registration.TunnelID != "" { |
| 349 | config.Logger.Info("Tunnel ID: " + registration.TunnelID) |
| 350 | } |
| 351 | |
| 352 | // Print out the user's trial zone URL in a nice box (if they requested and got one) |
| 353 | if isTrialTunnel := config.Hostname == ""; isTrialTunnel { |
| 354 | if url, err := url.Parse(registration.Url); err == nil { |
| 355 | for _, line := range asciiBox(trialZoneMsg(url.String()), 2) { |
| 356 | config.Logger.Infoln(line) |
| 357 | } |
| 358 | } else { |
| 359 | config.Logger.Errorln("Failed to connect tunnel, please try again.") |
| 360 | return fmt.Errorf("empty URL in response from Cloudflare edge") |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | config.Logger.Infof("Route propagating, it may take up to 1 minute for your new route to become functional") |
| 365 | return nil |
| 366 | } |
| 367 | |
| 368 | func UnregisterTunnel(muxer *h2mux.Muxer, gracePeriod time.Duration, logger *log.Logger) error { |
| 369 | logger.Debug("initiating RPC stream to unregister") |
| 370 | stream, err := muxer.OpenStream([]h2mux.Header{ |
| 371 | {Name: ":method", Value: "RPC"}, |
| 372 | {Name: ":scheme", Value: "capnp"}, |
| 373 | {Name: ":path", Value: "*"}, |
| 374 | }, nil) |
| 375 | if err != nil { |
| 376 | // RPC stream open error |
| 377 | return err |
| 378 | } |
| 379 | if !IsRPCStreamResponse(stream.Headers) { |
| 380 | // stream response error |
| 381 | return err |
| 382 | } |
| 383 | ctx := context.Background() |
| 384 | conn := rpc.NewConn( |
| 385 | tunnelrpc.NewTransportLogger(logger.WithField("subsystem", "rpc-unregister"), rpc.StreamTransport(stream)), |
| 386 | tunnelrpc.ConnLog(logger.WithField("subsystem", "rpc-transport")), |
| 387 | ) |
| 388 | defer conn.Close() |
| 389 | ts := tunnelpogs.TunnelServer_PogsClient{Client: conn.Bootstrap(ctx)} |
| 390 | // gracePeriod is encoded in int64 using capnproto |
| 391 | return ts.UnregisterTunnel(ctx, gracePeriod.Nanoseconds()) |
| 392 | } |
| 393 | |
| 394 | func LogServerInfo( |
| 395 | promise tunnelrpc.ServerInfo_Promise, |
| 396 | connectionID uint8, |
| 397 | metrics *TunnelMetrics, |
| 398 | logger *log.Logger, |
| 399 | ) { |
| 400 | serverInfoMessage, err := promise.Struct() |
| 401 | if err != nil { |
| 402 | logger.WithError(err).Warn("Failed to retrieve server information") |
| 403 | return |
| 404 | } |
| 405 | serverInfo, err := tunnelpogs.UnmarshalServerInfo(serverInfoMessage) |
| 406 | if err != nil { |
| 407 | logger.WithError(err).Warn("Failed to retrieve server information") |
| 408 | return |
| 409 | } |
| 410 | logger.Infof("Connected to %s", serverInfo.LocationName) |
| 411 | metrics.registerServerLocation(uint8ToString(connectionID), serverInfo.LocationName) |
| 412 | } |
| 413 | |
| 414 | func H2RequestHeadersToH1Request(h2 []h2mux.Header, h1 *http.Request) error { |
| 415 | for _, header := range h2 { |
| 416 | switch header.Name { |
| 417 | case ":method": |
| 418 | h1.Method = header.Value |
| 419 | case ":scheme": |
| 420 | case ":authority": |
| 421 | // Otherwise the host header will be based on the origin URL |
| 422 | h1.Host = header.Value |
| 423 | case ":path": |
| 424 | u, err := url.Parse(header.Value) |
| 425 | if err != nil { |
| 426 | return fmt.Errorf("unparseable path") |
| 427 | } |
| 428 | resolved := h1.URL.ResolveReference(u) |
| 429 | // prevent escaping base URL |
| 430 | if !strings.HasPrefix(resolved.String(), h1.URL.String()) { |
| 431 | return fmt.Errorf("invalid path") |
| 432 | } |
| 433 | h1.URL = resolved |
| 434 | case "content-length": |
| 435 | contentLength, err := strconv.ParseInt(header.Value, 10, 64) |
| 436 | if err != nil { |
| 437 | return fmt.Errorf("unparseable content length") |
| 438 | } |
| 439 | h1.ContentLength = contentLength |
| 440 | default: |
| 441 | h1.Header.Add(http.CanonicalHeaderKey(header.Name), header.Value) |
| 442 | } |
| 443 | } |
| 444 | return nil |
| 445 | } |
| 446 | |
| 447 | func H1ResponseToH2Response(h1 *http.Response) (h2 []h2mux.Header) { |
| 448 | h2 = []h2mux.Header{{Name: ":status", Value: fmt.Sprintf("%d", h1.StatusCode)}} |
| 449 | for headerName, headerValues := range h1.Header { |
| 450 | for _, headerValue := range headerValues { |
| 451 | h2 = append(h2, h2mux.Header{Name: strings.ToLower(headerName), Value: headerValue}) |
| 452 | } |
| 453 | } |
| 454 | return |
| 455 | } |
| 456 | |
| 457 | func FindCfRayHeader(h1 *http.Request) string { |
| 458 | return h1.Header.Get("Cf-Ray") |
| 459 | } |
| 460 | |
| 461 | type TunnelHandler struct { |
| 462 | originUrl string |
| 463 | muxer *h2mux.Muxer |
| 464 | httpClient http.RoundTripper |
| 465 | tlsConfig *tls.Config |
| 466 | tags []tunnelpogs.Tag |
| 467 | metrics *TunnelMetrics |
| 468 | // connectionID is only used by metrics, and prometheus requires labels to be string |
| 469 | connectionID string |
| 470 | logger *log.Logger |
| 471 | noChunkedEncoding bool |
| 472 | } |
| 473 | |
| 474 | var dialer = net.Dialer{DualStack: true} |
| 475 | |
| 476 | // NewTunnelHandler returns a TunnelHandler, origin LAN IP and error |
| 477 | func NewTunnelHandler(ctx context.Context, |
| 478 | config *TunnelConfig, |
| 479 | addr string, |
| 480 | connectionID uint8, |
| 481 | ) (*TunnelHandler, string, error) { |
| 482 | originURL, err := validation.ValidateUrl(config.OriginUrl) |
| 483 | if err != nil { |
| 484 | return nil, "", fmt.Errorf("unable to parse origin URL %#v", originURL) |
| 485 | } |
| 486 | h := &TunnelHandler{ |
| 487 | originUrl: originURL, |
| 488 | httpClient: config.HTTPTransport, |
| 489 | tlsConfig: config.ClientTlsConfig, |
| 490 | tags: config.Tags, |
| 491 | metrics: config.Metrics, |
| 492 | connectionID: uint8ToString(connectionID), |
| 493 | logger: config.Logger, |
| 494 | noChunkedEncoding: config.NoChunkedEncoding, |
| 495 | } |
| 496 | if h.httpClient == nil { |
| 497 | h.httpClient = http.DefaultTransport |
| 498 | } |
| 499 | // Inherit from parent context so we can cancel (Ctrl-C) while dialing |
| 500 | dialCtx, dialCancel := context.WithTimeout(ctx, dialTimeout) |
| 501 | // TUN-92: enforce a timeout on dial and handshake (as tls.Dial does not support one) |
| 502 | plaintextEdgeConn, err := dialer.DialContext(dialCtx, "tcp", addr) |
| 503 | dialCancel() |
| 504 | if err != nil { |
| 505 | return nil, "", dialError{cause: errors.Wrap(err, "DialContext error")} |
| 506 | } |
| 507 | edgeConn := tls.Client(plaintextEdgeConn, config.TlsConfig) |
| 508 | edgeConn.SetDeadline(time.Now().Add(dialTimeout)) |
| 509 | err = edgeConn.Handshake() |
| 510 | if err != nil { |
| 511 | return nil, "", dialError{cause: errors.Wrap(err, "Handshake with edge error")} |
| 512 | } |
| 513 | // clear the deadline on the conn; h2mux has its own timeouts |
| 514 | edgeConn.SetDeadline(time.Time{}) |
| 515 | // Establish a muxed connection with the edge |
| 516 | // Client mux handshake with agent server |
| 517 | h.muxer, err = h2mux.Handshake(edgeConn, edgeConn, h2mux.MuxerConfig{ |
| 518 | Timeout: 5 * time.Second, |
| 519 | Handler: h, |
| 520 | IsClient: true, |
| 521 | HeartbeatInterval: config.HeartbeatInterval, |
| 522 | MaxHeartbeats: config.MaxHeartbeats, |
| 523 | Logger: config.ProtocolLogger.WithFields(log.Fields{}), |
| 524 | CompressionQuality: h2mux.CompressionSetting(config.CompressionQuality), |
| 525 | }) |
| 526 | if err != nil { |
| 527 | return h, "", errors.New("TLS handshake error") |
| 528 | } |
| 529 | return h, edgeConn.LocalAddr().String(), err |
| 530 | } |
| 531 | |
| 532 | func (h *TunnelHandler) AppendTagHeaders(r *http.Request) { |
| 533 | for _, tag := range h.tags { |
| 534 | r.Header.Add(TagHeaderNamePrefix+tag.Name, tag.Value) |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | func (h *TunnelHandler) ServeStream(stream *h2mux.MuxedStream) error { |
| 539 | h.metrics.incrementRequests(h.connectionID) |
| 540 | req, err := http.NewRequest("GET", h.originUrl, h2mux.MuxedStreamReader{MuxedStream: stream}) |
| 541 | if err != nil { |
| 542 | h.logger.WithError(err).Panic("Unexpected error from http.NewRequest") |
| 543 | } |
| 544 | err = H2RequestHeadersToH1Request(stream.Headers, req) |
| 545 | if err != nil { |
| 546 | h.logger.WithError(err).Error("invalid request received") |
| 547 | } |
| 548 | h.AppendTagHeaders(req) |
| 549 | cfRay := FindCfRayHeader(req) |
| 550 | lbProbe := isLBProbeRequest(req) |
| 551 | h.logRequest(req, cfRay, lbProbe) |
| 552 | if websocket.IsWebSocketUpgrade(req) { |
| 553 | conn, response, err := websocket.ClientConnect(req, h.tlsConfig) |
| 554 | if err != nil { |
| 555 | h.logError(stream, err) |
| 556 | } else { |
| 557 | stream.WriteHeaders(H1ResponseToH2Response(response)) |
| 558 | defer conn.Close() |
| 559 | // Copy to/from stream to the undelying connection. Use the underlying |
| 560 | // connection because cloudflared doesn't operate on the message themselves |
| 561 | websocket.Stream(conn.UnderlyingConn(), stream) |
| 562 | h.metrics.incrementResponses(h.connectionID, "200") |
| 563 | h.logResponse(response, cfRay, lbProbe) |
| 564 | } |
| 565 | } else { |
| 566 | // Support for WSGI Servers by switching transfer encoding from chunked to gzip/deflate |
| 567 | if h.noChunkedEncoding { |
| 568 | req.TransferEncoding = []string{"gzip", "deflate"} |
| 569 | cLength, err := strconv.Atoi(req.Header.Get("Content-Length")) |
| 570 | if err == nil { |
| 571 | req.ContentLength = int64(cLength) |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | // Request origin to keep connection alive to improve performance |
| 576 | req.Header.Set("Connection", "keep-alive") |
| 577 | |
| 578 | response, err := h.httpClient.RoundTrip(req) |
| 579 | |
| 580 | if err != nil { |
| 581 | h.logError(stream, err) |
| 582 | } else { |
| 583 | defer response.Body.Close() |
| 584 | stream.WriteHeaders(H1ResponseToH2Response(response)) |
| 585 | if h.isEventStream(response) { |
| 586 | h.writeEventStream(stream, response.Body) |
| 587 | } else { |
| 588 | // Use CopyBuffer, because Copy only allocates a 32KiB buffer, and cross-stream |
| 589 | // compression generates dictionary on first write |
| 590 | io.CopyBuffer(stream, response.Body, make([]byte, 512*1024)) |
| 591 | } |
| 592 | |
| 593 | h.metrics.incrementResponses(h.connectionID, "200") |
| 594 | h.logResponse(response, cfRay, lbProbe) |
| 595 | } |
| 596 | } |
| 597 | h.metrics.decrementConcurrentRequests(h.connectionID) |
| 598 | return nil |
| 599 | } |
| 600 | |
| 601 | func (h *TunnelHandler) writeEventStream(stream *h2mux.MuxedStream, responseBody io.ReadCloser) { |
| 602 | reader := bufio.NewReader(responseBody) |
| 603 | for { |
| 604 | line, err := reader.ReadBytes('\n') |
| 605 | if err != nil { |
| 606 | break |
| 607 | } |
| 608 | stream.Write(line) |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | func (h *TunnelHandler) isEventStream(response *http.Response) bool { |
| 613 | if response.Header.Get("content-type") == "text/event-stream" { |
| 614 | h.logger.Debug("Detected Server-Side Events from Origin") |
| 615 | return true |
| 616 | } |
| 617 | return false |
| 618 | } |
| 619 | |
| 620 | func (h *TunnelHandler) logError(stream *h2mux.MuxedStream, err error) { |
| 621 | h.logger.WithError(err).Error("HTTP request error") |
| 622 | stream.WriteHeaders([]h2mux.Header{{Name: ":status", Value: "502"}}) |
| 623 | stream.Write([]byte("502 Bad Gateway")) |
| 624 | h.metrics.incrementResponses(h.connectionID, "502") |
| 625 | } |
| 626 | |
| 627 | func (h *TunnelHandler) logRequest(req *http.Request, cfRay string, lbProbe bool) { |
| 628 | if cfRay != "" { |
| 629 | h.logger.WithField("CF-RAY", cfRay).Debugf("%s %s %s", req.Method, req.URL, req.Proto) |
| 630 | } else if lbProbe { |
| 631 | h.logger.Debugf("Load Balancer health check %s %s %s", req.Method, req.URL, req.Proto) |
| 632 | } else { |
| 633 | h.logger.Warnf("All requests should have a CF-RAY header. Please open a support ticket with Cloudflare. %s %s %s ", req.Method, req.URL, req.Proto) |
| 634 | } |
| 635 | h.logger.Debugf("Request Headers %+v", req.Header) |
| 636 | } |
| 637 | |
| 638 | func (h *TunnelHandler) logResponse(r *http.Response, cfRay string, lbProbe bool) { |
| 639 | if cfRay != "" { |
| 640 | h.logger.WithField("CF-RAY", cfRay).Debugf("%s", r.Status) |
| 641 | } else if lbProbe { |
| 642 | h.logger.Debugf("Response to Load Balancer health check %s", r.Status) |
| 643 | } else { |
| 644 | h.logger.Infof("%s", r.Status) |
| 645 | } |
| 646 | h.logger.Debugf("Response Headers %+v", r.Header) |
| 647 | } |
| 648 | |
| 649 | func (h *TunnelHandler) UpdateMetrics(connectionID string) { |
| 650 | h.metrics.updateMuxerMetrics(connectionID, h.muxer.Metrics()) |
| 651 | } |
| 652 | |
| 653 | func uint8ToString(input uint8) string { |
| 654 | return strconv.FormatUint(uint64(input), 10) |
| 655 | } |
| 656 | |
| 657 | func isLBProbeRequest(req *http.Request) bool { |
| 658 | return strings.HasPrefix(req.UserAgent(), lbProbeUserAgentPrefix) |
| 659 | } |
| 660 | |
| 661 | // Print out the given lines in a nice ASCII box. |
| 662 | func asciiBox(lines []string, padding int) (box []string) { |
| 663 | maxLen := maxLen(lines) |
| 664 | spacer := strings.Repeat(" ", padding) |
| 665 | |
| 666 | border := "+" + strings.Repeat("-", maxLen+(padding*2)) + "+" |
| 667 | |
| 668 | box = append(box, border) |
| 669 | for _, line := range lines { |
| 670 | box = append(box, "|"+spacer+line+strings.Repeat(" ", maxLen-len(line))+spacer+"|") |
| 671 | } |
| 672 | box = append(box, border) |
| 673 | return |
| 674 | } |
| 675 | |
| 676 | func maxLen(lines []string) int { |
| 677 | max := 0 |
| 678 | for _, line := range lines { |
| 679 | if len(line) > max { |
| 680 | max = len(line) |
| 681 | } |
| 682 | } |
| 683 | return max |
| 684 | } |
| 685 | |
| 686 | func trialZoneMsg(url string) []string { |
| 687 | return []string{ |
| 688 | "Your free tunnel has started! Visit it:", |
| 689 | " " + url, |
| 690 | } |
| 691 | } |
| 692 | |