2020-10-08 10:12:26 +00:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-01-20 19:41:09 +00:00
|
|
|
"io"
|
2020-10-08 10:12:26 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2020-11-25 06:55:13 +00:00
|
|
|
"github.com/rs/zerolog"
|
2020-10-08 10:12:26 +00:00
|
|
|
"golang.org/x/sync/errgroup"
|
2021-03-23 14:30:43 +00:00
|
|
|
|
|
|
|
"github.com/cloudflare/cloudflared/h2mux"
|
2022-04-06 23:20:29 +00:00
|
|
|
"github.com/cloudflare/cloudflared/tracing"
|
2021-03-23 14:30:43 +00:00
|
|
|
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
|
|
|
"github.com/cloudflare/cloudflared/websocket"
|
2020-10-08 10:12:26 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
muxerTimeout = 5 * time.Second
|
|
|
|
openStreamTimeout = 30 * time.Second
|
|
|
|
)
|
|
|
|
|
|
|
|
type h2muxConnection struct {
|
2022-02-11 10:49:06 +00:00
|
|
|
orchestrator Orchestrator
|
|
|
|
gracePeriod time.Duration
|
|
|
|
muxerConfig *MuxerConfig
|
|
|
|
muxer *h2mux.Muxer
|
2020-10-08 10:12:26 +00:00
|
|
|
// connectionID is only used by metrics, and prometheus requires labels to be string
|
|
|
|
connIndexStr string
|
|
|
|
connIndex uint8
|
|
|
|
|
2021-01-20 19:41:09 +00:00
|
|
|
observer *Observer
|
2021-02-05 00:07:49 +00:00
|
|
|
gracefulShutdownC <-chan struct{}
|
2021-01-20 19:41:09 +00:00
|
|
|
stoppedGracefully bool
|
|
|
|
|
2021-07-16 15:14:37 +00:00
|
|
|
log *zerolog.Logger
|
|
|
|
|
2021-01-20 19:41:09 +00:00
|
|
|
// newRPCClientFunc allows us to mock RPCs during testing
|
|
|
|
newRPCClientFunc func(context.Context, io.ReadWriteCloser, *zerolog.Logger) NamedTunnelRPCClient
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type MuxerConfig struct {
|
|
|
|
HeartbeatInterval time.Duration
|
|
|
|
MaxHeartbeats uint64
|
|
|
|
CompressionSetting h2mux.CompressionSetting
|
|
|
|
MetricsUpdateFreq time.Duration
|
|
|
|
}
|
|
|
|
|
2020-11-25 06:55:13 +00:00
|
|
|
func (mc *MuxerConfig) H2MuxerConfig(h h2mux.MuxedStreamHandler, log *zerolog.Logger) *h2mux.MuxerConfig {
|
2020-10-08 10:12:26 +00:00
|
|
|
return &h2mux.MuxerConfig{
|
|
|
|
Timeout: muxerTimeout,
|
|
|
|
Handler: h,
|
|
|
|
IsClient: true,
|
|
|
|
HeartbeatInterval: mc.HeartbeatInterval,
|
|
|
|
MaxHeartbeats: mc.MaxHeartbeats,
|
2020-11-25 06:55:13 +00:00
|
|
|
Log: log,
|
2020-10-08 10:12:26 +00:00
|
|
|
CompressionQuality: mc.CompressionSetting,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewTunnelHandler returns a TunnelHandler, origin LAN IP and error
|
2020-12-28 18:10:01 +00:00
|
|
|
func NewH2muxConnection(
|
2022-02-11 10:49:06 +00:00
|
|
|
orchestrator Orchestrator,
|
2022-02-07 09:42:07 +00:00
|
|
|
gracePeriod time.Duration,
|
2020-10-08 10:12:26 +00:00
|
|
|
muxerConfig *MuxerConfig,
|
|
|
|
edgeConn net.Conn,
|
|
|
|
connIndex uint8,
|
|
|
|
observer *Observer,
|
2021-02-05 00:07:49 +00:00
|
|
|
gracefulShutdownC <-chan struct{},
|
2022-07-26 21:00:53 +00:00
|
|
|
log *zerolog.Logger,
|
2020-10-08 10:12:26 +00:00
|
|
|
) (*h2muxConnection, error, bool) {
|
|
|
|
h := &h2muxConnection{
|
2022-02-11 10:49:06 +00:00
|
|
|
orchestrator: orchestrator,
|
2022-02-07 09:42:07 +00:00
|
|
|
gracePeriod: gracePeriod,
|
2021-01-20 19:41:09 +00:00
|
|
|
muxerConfig: muxerConfig,
|
|
|
|
connIndexStr: uint8ToString(connIndex),
|
|
|
|
connIndex: connIndex,
|
|
|
|
observer: observer,
|
|
|
|
gracefulShutdownC: gracefulShutdownC,
|
|
|
|
newRPCClientFunc: newRegistrationRPCClient,
|
2022-07-26 21:00:53 +00:00
|
|
|
log: log,
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Establish a muxed connection with the edge
|
|
|
|
// Client mux handshake with agent server
|
2021-02-03 18:32:54 +00:00
|
|
|
muxer, err := h2mux.Handshake(edgeConn, edgeConn, *muxerConfig.H2MuxerConfig(h, observer.logTransport), h2mux.ActiveStreams)
|
2020-10-08 10:12:26 +00:00
|
|
|
if err != nil {
|
|
|
|
recoverable := isHandshakeErrRecoverable(err, connIndex, observer)
|
|
|
|
return nil, err, recoverable
|
|
|
|
}
|
|
|
|
h.muxer = muxer
|
|
|
|
return h, nil, false
|
|
|
|
}
|
|
|
|
|
2022-02-07 09:42:07 +00:00
|
|
|
func (h *h2muxConnection) ServeNamedTunnel(ctx context.Context, namedTunnel *NamedTunnelProperties, connOptions *tunnelpogs.ConnectionOptions, connectedFuse ConnectedFuse) error {
|
2020-10-08 10:12:26 +00:00
|
|
|
errGroup, serveCtx := errgroup.WithContext(ctx)
|
|
|
|
errGroup.Go(func() error {
|
|
|
|
return h.serveMuxer(serveCtx)
|
|
|
|
})
|
|
|
|
|
|
|
|
errGroup.Go(func() error {
|
2021-01-20 19:41:09 +00:00
|
|
|
if err := h.registerNamedTunnel(serveCtx, namedTunnel, connOptions); err != nil {
|
2020-10-08 10:12:26 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
connectedFuse.Connected()
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
errGroup.Go(func() error {
|
|
|
|
h.controlLoop(serveCtx, connectedFuse, true)
|
|
|
|
return nil
|
|
|
|
})
|
2021-01-27 13:19:37 +00:00
|
|
|
|
|
|
|
err := errGroup.Wait()
|
|
|
|
if err == errMuxerStopped {
|
|
|
|
if h.stoppedGracefully {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
h.observer.log.Info().Uint8(LogFieldConnIndex, h.connIndex).Msg("Unexpected muxer shutdown")
|
|
|
|
}
|
|
|
|
return err
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
2023-02-01 14:01:59 +00:00
|
|
|
func (h *h2muxConnection) ServeClassicTunnel(ctx context.Context, classicTunnel *ClassicTunnelProperties, credentialManager CredentialManager, registrationOptions *tunnelpogs.RegistrationOptions, connectedFuse ConnectedFuse) error {
|
|
|
|
errGroup, serveCtx := errgroup.WithContext(ctx)
|
|
|
|
errGroup.Go(func() error {
|
|
|
|
return h.serveMuxer(serveCtx)
|
|
|
|
})
|
|
|
|
|
|
|
|
errGroup.Go(func() (err error) {
|
|
|
|
defer func() {
|
|
|
|
if err == nil {
|
|
|
|
connectedFuse.Connected()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
if classicTunnel.UseReconnectToken && connectedFuse.IsConnected() {
|
|
|
|
err := h.reconnectTunnel(ctx, credentialManager, classicTunnel, registrationOptions)
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// log errors and proceed to RegisterTunnel
|
|
|
|
h.observer.log.Err(err).
|
|
|
|
Uint8(LogFieldConnIndex, h.connIndex).
|
|
|
|
Msg("Couldn't reconnect connection. Re-registering it instead.")
|
|
|
|
}
|
|
|
|
return h.registerTunnel(ctx, credentialManager, classicTunnel, registrationOptions)
|
|
|
|
})
|
|
|
|
|
|
|
|
errGroup.Go(func() error {
|
|
|
|
h.controlLoop(serveCtx, connectedFuse, false)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
err := errGroup.Wait()
|
|
|
|
if err == errMuxerStopped {
|
|
|
|
if h.stoppedGracefully {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
h.observer.log.Info().Uint8(LogFieldConnIndex, h.connIndex).Msg("Unexpected muxer shutdown")
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-10-08 10:12:26 +00:00
|
|
|
func (h *h2muxConnection) serveMuxer(ctx context.Context) error {
|
|
|
|
// All routines should stop when muxer finish serving. When muxer is shutdown
|
|
|
|
// gracefully, it doesn't return an error, so we need to return errMuxerShutdown
|
|
|
|
// here to notify other routines to stop
|
|
|
|
err := h.muxer.Serve(ctx)
|
|
|
|
if err == nil {
|
2021-01-20 17:52:35 +00:00
|
|
|
return errMuxerStopped
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *h2muxConnection) controlLoop(ctx context.Context, connectedFuse ConnectedFuse, isNamedTunnel bool) {
|
2021-05-25 17:07:06 +00:00
|
|
|
updateMetricsTicker := time.NewTicker(h.muxerConfig.MetricsUpdateFreq)
|
|
|
|
defer updateMetricsTicker.Stop()
|
2021-02-05 00:07:49 +00:00
|
|
|
var shutdownCompleted <-chan struct{}
|
2020-10-08 10:12:26 +00:00
|
|
|
for {
|
|
|
|
select {
|
2021-01-20 19:41:09 +00:00
|
|
|
case <-h.gracefulShutdownC:
|
|
|
|
if connectedFuse.IsConnected() {
|
|
|
|
h.unregister(isNamedTunnel)
|
|
|
|
}
|
|
|
|
h.stoppedGracefully = true
|
|
|
|
h.gracefulShutdownC = nil
|
2021-02-05 00:07:49 +00:00
|
|
|
shutdownCompleted = h.muxer.Shutdown()
|
|
|
|
|
|
|
|
case <-shutdownCompleted:
|
|
|
|
return
|
2021-01-20 19:41:09 +00:00
|
|
|
|
2020-10-08 10:12:26 +00:00
|
|
|
case <-ctx.Done():
|
|
|
|
// UnregisterTunnel blocks until the RPC call returns
|
2021-01-20 19:41:09 +00:00
|
|
|
if !h.stoppedGracefully && connectedFuse.IsConnected() {
|
2020-10-08 10:12:26 +00:00
|
|
|
h.unregister(isNamedTunnel)
|
|
|
|
}
|
|
|
|
h.muxer.Shutdown()
|
2021-02-05 00:07:49 +00:00
|
|
|
// don't wait for shutdown to finish when context is closed, this is the hard termination path
|
2020-10-08 10:12:26 +00:00
|
|
|
return
|
2021-01-20 19:41:09 +00:00
|
|
|
|
2021-05-25 17:07:06 +00:00
|
|
|
case <-updateMetricsTicker.C:
|
2020-10-08 10:12:26 +00:00
|
|
|
h.observer.metrics.updateMuxerMetrics(h.connIndexStr, h.muxer.Metrics())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *h2muxConnection) newRPCStream(ctx context.Context, rpcName rpcName) (*h2mux.MuxedStream, error) {
|
|
|
|
openStreamCtx, openStreamCancel := context.WithTimeout(ctx, openStreamTimeout)
|
|
|
|
defer openStreamCancel()
|
|
|
|
stream, err := h.muxer.OpenRPCStream(openStreamCtx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return stream, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *h2muxConnection) ServeStream(stream *h2mux.MuxedStream) error {
|
|
|
|
respWriter := &h2muxRespWriter{stream}
|
|
|
|
|
|
|
|
req, reqErr := h.newRequest(stream)
|
|
|
|
if reqErr != nil {
|
2020-10-27 22:27:15 +00:00
|
|
|
respWriter.WriteErrorResponse()
|
2020-10-08 10:12:26 +00:00
|
|
|
return reqErr
|
|
|
|
}
|
|
|
|
|
2021-01-11 19:59:45 +00:00
|
|
|
var sourceConnectionType = TypeHTTP
|
|
|
|
if websocket.IsWebSocketUpgrade(req) {
|
|
|
|
sourceConnectionType = TypeWebsocket
|
|
|
|
}
|
|
|
|
|
2022-02-11 10:49:06 +00:00
|
|
|
originProxy, err := h.orchestrator.GetOriginProxy()
|
|
|
|
if err != nil {
|
|
|
|
respWriter.WriteErrorResponse()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-07-26 21:00:53 +00:00
|
|
|
err = originProxy.ProxyHTTP(respWriter, tracing.NewTracedHTTPRequest(req, h.log), sourceConnectionType == TypeWebsocket)
|
2020-10-27 22:27:15 +00:00
|
|
|
if err != nil {
|
|
|
|
respWriter.WriteErrorResponse()
|
|
|
|
}
|
2021-07-16 15:14:37 +00:00
|
|
|
return err
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *h2muxConnection) newRequest(stream *h2mux.MuxedStream) (*http.Request, error) {
|
2020-11-02 11:21:34 +00:00
|
|
|
req, err := http.NewRequest("GET", "http://localhost:8080", h2mux.MuxedStreamReader{MuxedStream: stream})
|
2020-10-08 10:12:26 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "Unexpected error from http.NewRequest")
|
|
|
|
}
|
2021-03-26 04:04:56 +00:00
|
|
|
err = H2RequestHeadersToH1Request(stream.Headers, req)
|
2020-10-08 10:12:26 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "invalid request received")
|
|
|
|
}
|
|
|
|
return req, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type h2muxRespWriter struct {
|
|
|
|
*h2mux.MuxedStream
|
|
|
|
}
|
|
|
|
|
2022-08-16 11:21:58 +00:00
|
|
|
func (rp *h2muxRespWriter) AddTrailer(trailerName, trailerValue string) {
|
|
|
|
// do nothing. we don't support trailers over h2mux
|
|
|
|
}
|
|
|
|
|
2020-12-09 21:46:53 +00:00
|
|
|
func (rp *h2muxRespWriter) WriteRespHeaders(status int, header http.Header) error {
|
2021-03-26 04:04:56 +00:00
|
|
|
headers := H1ResponseToH2ResponseHeaders(status, header)
|
|
|
|
headers = append(headers, h2mux.Header{Name: ResponseMetaHeader, Value: responseMetaHeaderOrigin})
|
2020-10-16 10:13:48 +00:00
|
|
|
return rp.WriteHeaders(headers)
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|
|
|
|
|
2020-10-27 22:27:15 +00:00
|
|
|
func (rp *h2muxRespWriter) WriteErrorResponse() {
|
2020-11-25 06:55:13 +00:00
|
|
|
_ = rp.WriteHeaders([]h2mux.Header{
|
2020-10-08 10:12:26 +00:00
|
|
|
{Name: ":status", Value: "502"},
|
2021-03-26 04:04:56 +00:00
|
|
|
{Name: ResponseMetaHeader, Value: responseMetaHeaderCfd},
|
2020-10-08 10:12:26 +00:00
|
|
|
})
|
2020-11-25 06:55:13 +00:00
|
|
|
_, _ = rp.Write([]byte("502 Bad Gateway"))
|
2020-10-08 10:12:26 +00:00
|
|
|
}
|