2020-10-08 10:12:26 +00:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-01-20 19:41:09 +00:00
|
|
|
"fmt"
|
2020-10-08 10:12:26 +00:00
|
|
|
"io"
|
2020-10-16 10:13:48 +00:00
|
|
|
"math"
|
2020-10-08 10:12:26 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
2020-10-16 10:13:48 +00:00
|
|
|
"sync"
|
2020-10-08 10:12:26 +00:00
|
|
|
|
|
|
|
"github.com/cloudflare/cloudflared/h2mux"
|
|
|
|
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
|
|
|
|
2020-11-25 06:55:13 +00:00
|
|
|
"github.com/rs/zerolog"
|
2020-10-08 10:12:26 +00:00
|
|
|
"golang.org/x/net/http2"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
internalUpgradeHeader = "Cf-Cloudflared-Proxy-Connection-Upgrade"
|
|
|
|
websocketUpgrade = "websocket"
|
|
|
|
controlStreamUpgrade = "control-stream"
|
|
|
|
)
|
|
|
|
|
2021-01-20 19:41:09 +00:00
|
|
|
var errEdgeConnectionClosed = fmt.Errorf("connection with edge closed")
|
|
|
|
|
2020-10-27 22:27:15 +00:00
|
|
|
type http2Connection struct {
|
|
|
|
conn net.Conn
|
|
|
|
server *http2.Server
|
|
|
|
config *Config
|
|
|
|
namedTunnel *NamedTunnelConfig
|
|
|
|
connOptions *tunnelpogs.ConnectionOptions
|
|
|
|
observer *Observer
|
|
|
|
connIndexStr string
|
|
|
|
connIndex uint8
|
|
|
|
// newRPCClientFunc allows us to mock RPCs during testing
|
2021-01-27 13:19:37 +00:00
|
|
|
newRPCClientFunc func(context.Context, io.ReadWriteCloser, *zerolog.Logger) NamedTunnelRPCClient
|
|
|
|
|
|
|
|
activeRequestsWG sync.WaitGroup
|
2021-01-20 19:41:09 +00:00
|
|
|
connectedFuse ConnectedFuse
|
2021-02-05 00:07:49 +00:00
|
|
|
gracefulShutdownC <-chan struct{}
|
2021-01-20 19:41:09 +00:00
|
|
|
stoppedGracefully bool
|
2021-01-27 13:19:37 +00:00
|
|
|
controlStreamErr error // result of running control stream handler
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
2020-10-23 14:49:24 +00:00
|
|
|
func NewHTTP2Connection(
|
|
|
|
conn net.Conn,
|
|
|
|
config *Config,
|
|
|
|
namedTunnelConfig *NamedTunnelConfig,
|
|
|
|
connOptions *tunnelpogs.ConnectionOptions,
|
|
|
|
observer *Observer,
|
|
|
|
connIndex uint8,
|
|
|
|
connectedFuse ConnectedFuse,
|
2021-02-05 00:07:49 +00:00
|
|
|
gracefulShutdownC <-chan struct{},
|
2020-10-27 22:27:15 +00:00
|
|
|
) *http2Connection {
|
|
|
|
return &http2Connection{
|
2020-10-16 10:13:48 +00:00
|
|
|
conn: conn,
|
|
|
|
server: &http2.Server{
|
|
|
|
MaxConcurrentStreams: math.MaxUint32,
|
|
|
|
},
|
2021-01-20 19:41:09 +00:00
|
|
|
config: config,
|
|
|
|
namedTunnel: namedTunnelConfig,
|
|
|
|
connOptions: connOptions,
|
|
|
|
observer: observer,
|
|
|
|
connIndexStr: uint8ToString(connIndex),
|
|
|
|
connIndex: connIndex,
|
|
|
|
newRPCClientFunc: newRegistrationRPCClient,
|
|
|
|
connectedFuse: connectedFuse,
|
|
|
|
gracefulShutdownC: gracefulShutdownC,
|
2020-10-14 13:42:00 +00:00
|
|
|
}
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
2021-01-20 19:41:09 +00:00
|
|
|
func (c *http2Connection) Serve(ctx context.Context) error {
|
2020-10-08 10:12:26 +00:00
|
|
|
go func() {
|
|
|
|
<-ctx.Done()
|
|
|
|
c.close()
|
|
|
|
}()
|
|
|
|
c.server.ServeConn(c.conn, &http2.ServeConnOpts{
|
|
|
|
Context: ctx,
|
|
|
|
Handler: c,
|
|
|
|
})
|
2021-01-20 19:41:09 +00:00
|
|
|
|
2021-01-27 13:19:37 +00:00
|
|
|
switch {
|
|
|
|
case c.stoppedGracefully:
|
|
|
|
return nil
|
|
|
|
case c.controlStreamErr != nil:
|
|
|
|
return c.controlStreamErr
|
|
|
|
default:
|
|
|
|
c.observer.log.Info().Uint8(LogFieldConnIndex, c.connIndex).Msg("Lost connection with the edge")
|
2021-01-20 19:41:09 +00:00
|
|
|
return errEdgeConnectionClosed
|
|
|
|
}
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
2020-10-27 22:27:15 +00:00
|
|
|
func (c *http2Connection) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2021-01-27 13:19:37 +00:00
|
|
|
c.activeRequestsWG.Add(1)
|
|
|
|
defer c.activeRequestsWG.Done()
|
2020-10-16 10:13:48 +00:00
|
|
|
|
2020-10-08 10:12:26 +00:00
|
|
|
respWriter := &http2RespWriter{
|
|
|
|
r: r.Body,
|
|
|
|
w: w,
|
|
|
|
}
|
2020-10-23 14:49:24 +00:00
|
|
|
flusher, isFlusher := w.(http.Flusher)
|
|
|
|
if !isFlusher {
|
2020-11-25 06:55:13 +00:00
|
|
|
c.observer.log.Error().Msgf("%T doesn't implement http.Flusher", w)
|
2020-10-27 22:27:15 +00:00
|
|
|
respWriter.WriteErrorResponse()
|
2020-10-23 14:49:24 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
respWriter.flusher = flusher
|
2020-10-27 22:27:15 +00:00
|
|
|
var err error
|
2020-10-08 10:12:26 +00:00
|
|
|
if isControlStreamUpgrade(r) {
|
2020-10-23 14:49:24 +00:00
|
|
|
respWriter.shouldFlush = true
|
2020-10-27 22:27:15 +00:00
|
|
|
err = c.serveControlStream(r.Context(), respWriter)
|
2021-01-27 13:19:37 +00:00
|
|
|
c.controlStreamErr = err
|
2020-10-08 10:12:26 +00:00
|
|
|
} else if isWebsocketUpgrade(r) {
|
2020-10-23 14:49:24 +00:00
|
|
|
respWriter.shouldFlush = true
|
2020-10-08 10:12:26 +00:00
|
|
|
stripWebsocketUpgradeHeader(r)
|
2020-10-27 22:27:15 +00:00
|
|
|
err = c.config.OriginClient.Proxy(respWriter, r, true)
|
2020-10-08 10:12:26 +00:00
|
|
|
} else {
|
2020-10-27 22:27:15 +00:00
|
|
|
err = c.config.OriginClient.Proxy(respWriter, r, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
respWriter.WriteErrorResponse()
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-27 22:27:15 +00:00
|
|
|
func (c *http2Connection) serveControlStream(ctx context.Context, respWriter *http2RespWriter) error {
|
2020-11-25 06:55:13 +00:00
|
|
|
rpcClient := c.newRPCClientFunc(ctx, respWriter, c.observer.log)
|
2020-10-27 22:27:15 +00:00
|
|
|
defer rpcClient.Close()
|
2020-10-08 10:12:26 +00:00
|
|
|
|
2020-10-27 22:27:15 +00:00
|
|
|
if err := rpcClient.RegisterConnection(ctx, c.namedTunnel, c.connOptions, c.connIndex, c.observer); err != nil {
|
2020-10-08 10:12:26 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.connectedFuse.Connected()
|
|
|
|
|
2021-01-20 19:41:09 +00:00
|
|
|
// wait for connection termination or start of graceful shutdown
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
break
|
|
|
|
case <-c.gracefulShutdownC:
|
|
|
|
c.stoppedGracefully = true
|
|
|
|
}
|
|
|
|
|
2021-02-04 21:09:17 +00:00
|
|
|
c.observer.sendUnregisteringEvent(c.connIndex)
|
2020-10-27 22:27:15 +00:00
|
|
|
rpcClient.GracefulShutdown(ctx, c.config.GracePeriod)
|
2021-01-20 19:41:09 +00:00
|
|
|
c.observer.log.Info().Uint8(LogFieldConnIndex, c.connIndex).Msg("Unregistered tunnel connection")
|
2020-10-08 10:12:26 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-10-27 22:27:15 +00:00
|
|
|
func (c *http2Connection) close() {
|
2020-10-16 10:13:48 +00:00
|
|
|
// Wait for all serve HTTP handlers to return
|
2021-01-27 13:19:37 +00:00
|
|
|
c.activeRequestsWG.Wait()
|
2020-10-08 10:12:26 +00:00
|
|
|
c.conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
type http2RespWriter struct {
|
2020-10-23 14:49:24 +00:00
|
|
|
r io.Reader
|
|
|
|
w http.ResponseWriter
|
|
|
|
flusher http.Flusher
|
|
|
|
shouldFlush bool
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (rp *http2RespWriter) WriteRespHeaders(resp *http.Response) error {
|
|
|
|
dest := rp.w.Header()
|
|
|
|
userHeaders := make(http.Header, len(resp.Header))
|
|
|
|
for header, values := range resp.Header {
|
|
|
|
// Since these are http2 headers, they're required to be lowercase
|
|
|
|
h2name := strings.ToLower(header)
|
|
|
|
for _, v := range values {
|
|
|
|
if h2name == "content-length" {
|
|
|
|
// This header has meaning in HTTP/2 and will be used by the edge,
|
|
|
|
// so it should be sent as an HTTP/2 response header.
|
|
|
|
dest.Add(h2name, v)
|
|
|
|
// Since these are http2 headers, they're required to be lowercase
|
|
|
|
} else if !h2mux.IsControlHeader(h2name) || h2mux.IsWebsocketClientHeader(h2name) {
|
|
|
|
// User headers, on the other hand, must all be serialized so that
|
|
|
|
// HTTP/2 header validation won't be applied to HTTP/1 header values
|
|
|
|
userHeaders.Add(h2name, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Perform user header serialization and set them in the single header
|
2020-10-16 10:13:48 +00:00
|
|
|
dest.Set(canonicalResponseUserHeadersField, h2mux.SerializeHeaders(userHeaders))
|
2020-10-23 14:49:24 +00:00
|
|
|
rp.setResponseMetaHeader(responseMetaHeaderOrigin)
|
2020-10-08 10:12:26 +00:00
|
|
|
status := resp.StatusCode
|
|
|
|
// HTTP2 removes support for 101 Switching Protocols https://tools.ietf.org/html/rfc7540#section-8.1.1
|
|
|
|
if status == http.StatusSwitchingProtocols {
|
|
|
|
status = http.StatusOK
|
|
|
|
}
|
|
|
|
rp.w.WriteHeader(status)
|
2020-11-18 11:53:59 +00:00
|
|
|
if IsServerSentEvent(resp.Header) {
|
2020-10-23 14:49:24 +00:00
|
|
|
rp.shouldFlush = true
|
|
|
|
}
|
|
|
|
if rp.shouldFlush {
|
|
|
|
rp.flusher.Flush()
|
|
|
|
}
|
2020-10-08 10:12:26 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-10-27 22:27:15 +00:00
|
|
|
func (rp *http2RespWriter) WriteErrorResponse() {
|
2020-10-16 10:13:48 +00:00
|
|
|
rp.setResponseMetaHeader(responseMetaHeaderCfd)
|
2020-10-08 10:12:26 +00:00
|
|
|
rp.w.WriteHeader(http.StatusBadGateway)
|
|
|
|
}
|
|
|
|
|
2020-10-16 10:13:48 +00:00
|
|
|
func (rp *http2RespWriter) setResponseMetaHeader(value string) {
|
|
|
|
rp.w.Header().Set(canonicalResponseMetaHeaderField, value)
|
|
|
|
}
|
|
|
|
|
2020-10-08 10:12:26 +00:00
|
|
|
func (rp *http2RespWriter) Read(p []byte) (n int, err error) {
|
|
|
|
return rp.r.Read(p)
|
|
|
|
}
|
|
|
|
|
2020-10-23 14:49:24 +00:00
|
|
|
func (rp *http2RespWriter) Write(p []byte) (n int, err error) {
|
2020-10-30 11:41:14 +00:00
|
|
|
defer func() {
|
|
|
|
// Implementer of OriginClient should make sure it doesn't write to the connection after Proxy returns
|
|
|
|
// Register a recover routine just in case.
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
println("Recover from http2 response writer panic, error", r)
|
|
|
|
}
|
|
|
|
}()
|
2020-10-23 14:49:24 +00:00
|
|
|
n, err = rp.w.Write(p)
|
|
|
|
if err == nil && rp.shouldFlush {
|
|
|
|
rp.flusher.Flush()
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
2020-10-23 14:49:24 +00:00
|
|
|
return n, err
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
2020-10-23 14:49:24 +00:00
|
|
|
func (rp *http2RespWriter) Close() error {
|
2020-10-08 10:12:26 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func isControlStreamUpgrade(r *http.Request) bool {
|
|
|
|
return strings.ToLower(r.Header.Get(internalUpgradeHeader)) == controlStreamUpgrade
|
|
|
|
}
|
|
|
|
|
|
|
|
func isWebsocketUpgrade(r *http.Request) bool {
|
|
|
|
return strings.ToLower(r.Header.Get(internalUpgradeHeader)) == websocketUpgrade
|
|
|
|
}
|
|
|
|
|
|
|
|
func stripWebsocketUpgradeHeader(r *http.Request) {
|
|
|
|
r.Header.Del(internalUpgradeHeader)
|
|
|
|
}
|