cloudflared-mirror/origin/tunnel.go

535 lines
16 KiB
Go
Raw Normal View History

2017-10-16 11:44:03 +00:00
package origin
import (
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"runtime"
2017-11-28 13:41:29 +00:00
"strconv"
2017-10-16 11:44:03 +00:00
"strings"
2017-12-21 12:21:57 +00:00
"sync"
2017-10-16 11:44:03 +00:00
"time"
"golang.org/x/net/context"
2018-03-22 15:24:52 +00:00
"github.com/cloudflare/cloudflared/h2mux"
"github.com/cloudflare/cloudflared/tunnelrpc"
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
"github.com/cloudflare/cloudflared/validation"
"github.com/cloudflare/cloudflared/websocket"
2017-10-16 11:44:03 +00:00
raven "github.com/getsentry/raven-go"
"github.com/pkg/errors"
2017-11-28 13:41:29 +00:00
_ "github.com/prometheus/client_golang/prometheus"
2018-02-20 21:13:56 +00:00
"github.com/sirupsen/logrus"
2017-10-16 11:44:03 +00:00
rpc "zombiezen.com/go/capnproto2/rpc"
)
2018-02-20 21:13:56 +00:00
var Log *logrus.Logger
2017-10-16 11:44:03 +00:00
const (
dialTimeout = 15 * time.Second
2017-11-28 13:41:29 +00:00
TagHeaderNamePrefix = "Cf-Warp-Tag-"
DuplicateConnectionError = "EDUPCONN"
2017-10-16 11:44:03 +00:00
)
type TunnelConfig struct {
2017-11-28 13:41:29 +00:00
EdgeAddrs []string
2017-10-16 11:44:03 +00:00
OriginUrl string
Hostname string
2017-11-07 15:17:19 +00:00
OriginCert []byte
2017-10-16 11:44:03 +00:00
TlsConfig *tls.Config
2018-02-20 21:13:56 +00:00
ClientTlsConfig *tls.Config
2017-10-16 11:44:03 +00:00
Retries uint
HeartbeatInterval time.Duration
MaxHeartbeats uint64
ClientID string
ReportedVersion string
LBPool string
Tags []tunnelpogs.Tag
2017-11-28 13:41:29 +00:00
HAConnections int
2017-12-21 12:21:57 +00:00
HTTPTransport http.RoundTripper
2018-03-22 15:24:52 +00:00
Metrics *tunnelMetrics
2017-11-28 13:41:29 +00:00
MetricsUpdateFreq time.Duration
2018-02-20 21:13:56 +00:00
ProtocolLogger *logrus.Logger
Logger *logrus.Logger
IsAutoupdated bool
2018-04-04 15:47:36 +00:00
GracePeriod time.Duration
2017-10-16 11:44:03 +00:00
}
type dialError struct {
cause error
}
func (e dialError) Error() string {
return e.cause.Error()
}
2017-11-28 13:41:29 +00:00
type dupConnRegisterTunnelError struct{}
func (e dupConnRegisterTunnelError) Error() string {
return "already connected to this server"
}
2017-10-16 11:44:03 +00:00
type printableRegisterTunnelError struct {
cause error
permanent bool
}
func (e printableRegisterTunnelError) Error() string {
return e.cause.Error()
}
2017-11-28 13:41:29 +00:00
func (c *TunnelConfig) RegistrationOptions(connectionID uint8, OriginLocalIP string) *tunnelpogs.RegistrationOptions {
policy := tunnelrpc.ExistingTunnelPolicy_balance
if c.HAConnections <= 1 && c.LBPool == "" {
policy = tunnelrpc.ExistingTunnelPolicy_disconnect
2017-10-16 11:44:03 +00:00
}
return &tunnelpogs.RegistrationOptions{
ClientID: c.ClientID,
Version: c.ReportedVersion,
OS: fmt.Sprintf("%s_%s", runtime.GOOS, runtime.GOARCH),
ExistingTunnelPolicy: policy,
2018-02-20 21:13:56 +00:00
PoolName: c.LBPool,
2017-10-16 11:44:03 +00:00
Tags: c.Tags,
2017-11-28 13:41:29 +00:00
ConnectionID: connectionID,
OriginLocalIP: OriginLocalIP,
2018-02-20 21:13:56 +00:00
IsAutoupdated: c.IsAutoupdated,
2017-10-16 11:44:03 +00:00
}
}
2017-11-28 13:41:29 +00:00
func StartTunnelDaemon(config *TunnelConfig, shutdownC <-chan struct{}, connectedSignal chan struct{}) error {
2018-02-20 21:13:56 +00:00
Log = config.Logger
2017-10-16 11:44:03 +00:00
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-shutdownC
cancel()
}()
2017-12-21 12:21:57 +00:00
// If a user specified negative HAConnections, we will treat it as requesting 1 connection
2017-11-28 13:41:29 +00:00
if config.HAConnections > 1 {
return NewSupervisor(config).Run(ctx, connectedSignal)
} else {
addrs, err := ResolveEdgeIPs(config.EdgeAddrs)
if err != nil {
return err
}
return ServeTunnelLoop(ctx, config, addrs[0], 0, connectedSignal)
}
}
func ServeTunnelLoop(ctx context.Context, config *TunnelConfig, addr *net.TCPAddr, connectionID uint8, connectedSignal chan struct{}) error {
2017-12-21 12:21:57 +00:00
config.Metrics.incrementHaConnections()
defer config.Metrics.decrementHaConnections()
2017-10-16 11:44:03 +00:00
backoff := BackoffHandler{MaxRetries: config.Retries}
2017-11-28 13:41:29 +00:00
// Used to close connectedSignal no more than once
connectedFuse := h2mux.NewBooleanFuse()
go func() {
if connectedFuse.Await() {
close(connectedSignal)
}
}()
// Ensure the above goroutine will terminate if we return without connecting
defer connectedFuse.Fuse(false)
2017-10-16 11:44:03 +00:00
for {
2017-11-28 13:41:29 +00:00
err, recoverable := ServeTunnel(ctx, config, addr, connectionID, connectedFuse, &backoff)
2017-10-16 11:44:03 +00:00
if recoverable {
if duration, ok := backoff.GetBackoffDuration(ctx); ok {
2018-02-20 21:13:56 +00:00
Log.Infof("Retrying in %s seconds", duration)
2017-10-16 11:44:03 +00:00
backoff.Backoff(ctx)
continue
}
}
return err
}
}
func ServeTunnel(
ctx context.Context,
config *TunnelConfig,
2017-11-28 13:41:29 +00:00
addr *net.TCPAddr,
connectionID uint8,
connectedFuse *h2mux.BooleanFuse,
2017-10-16 11:44:03 +00:00
backoff *BackoffHandler,
) (err error, recoverable bool) {
2017-12-21 12:21:57 +00:00
var wg sync.WaitGroup
wg.Add(2)
2017-11-28 13:41:29 +00:00
// Treat panics as recoverable errors
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("ServeTunnel: %v", r)
}
recoverable = true
}
}()
2017-10-16 11:44:03 +00:00
// Returns error from parsing the origin URL or handshake errors
2017-11-28 13:41:29 +00:00
handler, originLocalIP, err := NewTunnelHandler(ctx, config, addr.String(), connectionID)
2017-10-16 11:44:03 +00:00
if err != nil {
2018-02-20 21:13:56 +00:00
errLog := Log.WithError(err)
2017-10-16 11:44:03 +00:00
switch err.(type) {
case dialError:
errLog.Error("Unable to dial edge")
case h2mux.MuxerHandshakeError:
errLog.Error("Handshake failed with edge server")
default:
errLog.Error("Tunnel creation failure")
return err, false
}
return err, true
}
serveCtx, serveCancel := context.WithCancel(ctx)
registerErrC := make(chan error, 1)
go func() {
2018-03-22 15:24:52 +00:00
defer wg.Done()
2017-11-28 13:41:29 +00:00
err := RegisterTunnel(serveCtx, handler.muxer, config, connectionID, originLocalIP)
2017-10-16 11:44:03 +00:00
if err == nil {
2017-11-28 13:41:29 +00:00
connectedFuse.Fuse(true)
2017-10-16 11:44:03 +00:00
backoff.SetGracePeriod()
} else {
serveCancel()
}
registerErrC <- err
}()
2017-11-28 13:41:29 +00:00
updateMetricsTickC := time.Tick(config.MetricsUpdateFreq)
2017-10-16 11:44:03 +00:00
go func() {
2017-12-21 12:21:57 +00:00
defer wg.Done()
2018-03-22 15:24:52 +00:00
connectionTag := uint8ToString(connectionID)
2017-11-28 13:41:29 +00:00
for {
select {
case <-serveCtx.Done():
2018-04-04 15:47:36 +00:00
// UnregisterTunnel blocks until the RPC call returns
UnregisterTunnel(handler.muxer, config.GracePeriod)
2017-11-28 13:41:29 +00:00
handler.muxer.Shutdown()
2017-12-21 12:21:57 +00:00
return
2017-11-28 13:41:29 +00:00
case <-updateMetricsTickC:
2018-03-22 15:24:52 +00:00
handler.UpdateMetrics(connectionTag)
2017-11-28 13:41:29 +00:00
}
}
2017-10-16 11:44:03 +00:00
}()
2017-11-28 13:41:29 +00:00
2017-10-16 11:44:03 +00:00
err = handler.muxer.Serve()
serveCancel()
registerErr := <-registerErrC
2017-12-21 12:21:57 +00:00
wg.Wait()
2017-10-16 11:44:03 +00:00
if err != nil {
2018-02-20 21:13:56 +00:00
Log.WithError(err).Error("Tunnel error")
2017-10-16 11:44:03 +00:00
return err, true
}
if registerErr != nil {
// Don't retry on errors like entitlement failure or version too old
if e, ok := registerErr.(printableRegisterTunnelError); ok {
2018-02-20 21:13:56 +00:00
Log.Error(e)
return e.cause, !e.permanent
2017-11-28 13:41:29 +00:00
} else if e, ok := registerErr.(dupConnRegisterTunnelError); ok {
2018-02-20 21:13:56 +00:00
Log.Info("Already connected to this server, selecting a different one")
2017-11-28 13:41:29 +00:00
return e, true
2017-10-16 11:44:03 +00:00
}
2017-11-07 15:17:19 +00:00
// Only log errors to Sentry that may have been caused by the client side, to reduce dupes
raven.CaptureError(registerErr, nil)
2018-02-20 21:13:56 +00:00
Log.Error("Cannot register")
2017-10-16 11:44:03 +00:00
return err, true
}
return nil, false
}
func IsRPCStreamResponse(headers []h2mux.Header) bool {
if len(headers) != 1 {
return false
}
if headers[0].Name != ":status" || headers[0].Value != "200" {
return false
}
return true
}
2017-11-28 13:41:29 +00:00
func RegisterTunnel(ctx context.Context, muxer *h2mux.Muxer, config *TunnelConfig, connectionID uint8, originLocalIP string) error {
2018-02-20 21:13:56 +00:00
logger := Log.WithField("subsystem", "rpc")
2018-04-04 15:47:36 +00:00
logger.Debug("initiating RPC stream to register")
2017-10-16 11:44:03 +00:00
stream, err := muxer.OpenStream([]h2mux.Header{
{Name: ":method", Value: "RPC"},
{Name: ":scheme", Value: "capnp"},
{Name: ":path", Value: "*"},
}, nil)
if err != nil {
// RPC stream open error
raven.CaptureError(err, nil)
return err
}
if !IsRPCStreamResponse(stream.Headers) {
// stream response error
raven.CaptureError(err, nil)
return err
}
conn := rpc.NewConn(
tunnelrpc.NewTransportLogger(logger, rpc.StreamTransport(stream)),
tunnelrpc.ConnLog(logger.WithField("subsystem", "rpc-transport")),
)
defer conn.Close()
ts := tunnelpogs.TunnelServer_PogsClient{Client: conn.Bootstrap(ctx)}
// Request server info without blocking tunnel registration; must use capnp library directly.
tsClient := tunnelrpc.TunnelServer{Client: ts.Client}
serverInfoPromise := tsClient.GetServerInfo(ctx, func(tunnelrpc.TunnelServer_getServerInfo_Params) error {
return nil
})
registration, err := ts.RegisterTunnel(
ctx,
2017-11-07 15:17:19 +00:00
config.OriginCert,
2017-10-16 11:44:03 +00:00
config.Hostname,
2017-11-28 13:41:29 +00:00
config.RegistrationOptions(connectionID, originLocalIP),
2017-10-16 11:44:03 +00:00
)
2017-11-28 13:41:29 +00:00
LogServerInfo(logger, serverInfoPromise.Result(), connectionID, config.Metrics)
2017-10-16 11:44:03 +00:00
if err != nil {
// RegisterTunnel RPC failure
return err
}
for _, logLine := range registration.LogLines {
logger.Info(logLine)
}
2017-11-28 13:41:29 +00:00
if registration.Err == DuplicateConnectionError {
return dupConnRegisterTunnelError{}
} else if registration.Err != "" {
2017-10-16 11:44:03 +00:00
return printableRegisterTunnelError{
cause: fmt.Errorf("Server error: %s", registration.Err),
permanent: registration.PermanentFailure,
}
}
2017-11-07 15:17:19 +00:00
2017-10-16 11:44:03 +00:00
return nil
}
2018-04-04 15:47:36 +00:00
func UnregisterTunnel(muxer *h2mux.Muxer, gracePeriod time.Duration) error {
logger := Log.WithField("subsystem", "rpc")
logger.Debug("initiating RPC stream to unregister")
stream, err := muxer.OpenStream([]h2mux.Header{
{Name: ":method", Value: "RPC"},
{Name: ":scheme", Value: "capnp"},
{Name: ":path", Value: "*"},
}, nil)
if err != nil {
// RPC stream open error
raven.CaptureError(err, nil)
return err
}
if !IsRPCStreamResponse(stream.Headers) {
// stream response error
raven.CaptureError(err, nil)
return err
}
ctx := context.Background()
conn := rpc.NewConn(
tunnelrpc.NewTransportLogger(logger, rpc.StreamTransport(stream)),
tunnelrpc.ConnLog(logger.WithField("subsystem", "rpc-transport")),
)
defer conn.Close()
ts := tunnelpogs.TunnelServer_PogsClient{Client: conn.Bootstrap(ctx)}
// gracePeriod is encoded in int64 using capnproto
return ts.UnregisterTunnel(ctx, gracePeriod.Nanoseconds())
}
2018-02-20 21:13:56 +00:00
func LogServerInfo(logger *logrus.Entry,
2017-11-28 13:41:29 +00:00
promise tunnelrpc.ServerInfo_Promise,
connectionID uint8,
2018-03-22 15:24:52 +00:00
metrics *tunnelMetrics,
2017-11-28 13:41:29 +00:00
) {
2017-10-16 11:44:03 +00:00
serverInfoMessage, err := promise.Struct()
if err != nil {
logger.WithError(err).Warn("Failed to retrieve server information")
return
}
serverInfo, err := tunnelpogs.UnmarshalServerInfo(serverInfoMessage)
if err != nil {
logger.WithError(err).Warn("Failed to retrieve server information")
return
}
2018-02-20 21:13:56 +00:00
Log.Infof("Connected to %s", serverInfo.LocationName)
2017-11-28 13:41:29 +00:00
metrics.registerServerLocation(uint8ToString(connectionID), serverInfo.LocationName)
}
func H2RequestHeadersToH1Request(h2 []h2mux.Header, h1 *http.Request) error {
for _, header := range h2 {
switch header.Name {
case ":method":
h1.Method = header.Value
case ":scheme":
case ":authority":
// Otherwise the host header will be based on the origin URL
h1.Host = header.Value
case ":path":
u, err := url.Parse(header.Value)
if err != nil {
return fmt.Errorf("unparseable path")
}
resolved := h1.URL.ResolveReference(u)
// prevent escaping base URL
if !strings.HasPrefix(resolved.String(), h1.URL.String()) {
return fmt.Errorf("invalid path")
}
h1.URL = resolved
default:
h1.Header.Add(http.CanonicalHeaderKey(header.Name), header.Value)
}
}
return nil
}
func H1ResponseToH2Response(h1 *http.Response) (h2 []h2mux.Header) {
h2 = []h2mux.Header{{Name: ":status", Value: fmt.Sprintf("%d", h1.StatusCode)}}
for headerName, headerValues := range h1.Header {
for _, headerValue := range headerValues {
h2 = append(h2, h2mux.Header{Name: strings.ToLower(headerName), Value: headerValue})
}
}
return
2017-10-16 11:44:03 +00:00
}
2018-03-22 15:24:52 +00:00
func FindCfRayHeader(h1 *http.Request) string {
return h1.Header.Get("Cf-Ray")
}
2017-10-16 11:44:03 +00:00
type TunnelHandler struct {
originUrl string
muxer *h2mux.Muxer
2017-12-21 12:21:57 +00:00
httpClient http.RoundTripper
2018-02-20 21:13:56 +00:00
tlsConfig *tls.Config
2017-10-16 11:44:03 +00:00
tags []tunnelpogs.Tag
2018-03-22 15:24:52 +00:00
metrics *tunnelMetrics
2017-11-28 13:41:29 +00:00
// connectionID is only used by metrics, and prometheus requires labels to be string
connectionID string
2017-10-16 11:44:03 +00:00
}
var dialer = net.Dialer{DualStack: true}
2017-11-28 13:41:29 +00:00
// NewTunnelHandler returns a TunnelHandler, origin LAN IP and error
func NewTunnelHandler(ctx context.Context, config *TunnelConfig, addr string, connectionID uint8) (*TunnelHandler, string, error) {
2017-10-16 11:44:03 +00:00
url, err := validation.ValidateUrl(config.OriginUrl)
if err != nil {
2017-11-28 13:41:29 +00:00
return nil, "", fmt.Errorf("Unable to parse origin url %#v", url)
2017-10-16 11:44:03 +00:00
}
h := &TunnelHandler{
2017-11-28 13:41:29 +00:00
originUrl: url,
2017-12-21 12:21:57 +00:00
httpClient: config.HTTPTransport,
2018-02-20 21:13:56 +00:00
tlsConfig: config.ClientTlsConfig,
2017-11-28 13:41:29 +00:00
tags: config.Tags,
metrics: config.Metrics,
connectionID: uint8ToString(connectionID),
2017-10-16 11:44:03 +00:00
}
2017-12-21 12:21:57 +00:00
if h.httpClient == nil {
h.httpClient = http.DefaultTransport
}
2017-10-16 11:44:03 +00:00
// Inherit from parent context so we can cancel (Ctrl-C) while dialing
dialCtx, dialCancel := context.WithTimeout(ctx, dialTimeout)
// TUN-92: enforce a timeout on dial and handshake (as tls.Dial does not support one)
2017-11-28 13:41:29 +00:00
plaintextEdgeConn, err := dialer.DialContext(dialCtx, "tcp", addr)
2017-10-16 11:44:03 +00:00
dialCancel()
if err != nil {
2017-12-21 12:21:57 +00:00
return nil, "", dialError{cause: errors.Wrap(err, "DialContext error")}
2017-10-16 11:44:03 +00:00
}
edgeConn := tls.Client(plaintextEdgeConn, config.TlsConfig)
edgeConn.SetDeadline(time.Now().Add(dialTimeout))
err = edgeConn.Handshake()
if err != nil {
2017-12-21 12:21:57 +00:00
return nil, "", dialError{cause: errors.Wrap(err, "Handshake with edge error")}
2017-10-16 11:44:03 +00:00
}
// clear the deadline on the conn; h2mux has its own timeouts
edgeConn.SetDeadline(time.Time{})
// Establish a muxed connection with the edge
// Client mux handshake with agent server
h.muxer, err = h2mux.Handshake(edgeConn, edgeConn, h2mux.MuxerConfig{
Timeout: 5 * time.Second,
Handler: h,
IsClient: true,
HeartbeatInterval: config.HeartbeatInterval,
MaxHeartbeats: config.MaxHeartbeats,
2017-11-28 13:41:29 +00:00
Logger: config.ProtocolLogger,
2017-10-16 11:44:03 +00:00
})
if err != nil {
2017-11-28 13:41:29 +00:00
return h, "", errors.New("TLS handshake error")
2017-10-16 11:44:03 +00:00
}
2017-11-28 13:41:29 +00:00
return h, edgeConn.LocalAddr().String(), err
2017-10-16 11:44:03 +00:00
}
func (h *TunnelHandler) AppendTagHeaders(r *http.Request) {
for _, tag := range h.tags {
r.Header.Add(TagHeaderNamePrefix+tag.Name, tag.Value)
}
}
func (h *TunnelHandler) ServeStream(stream *h2mux.MuxedStream) error {
2017-11-28 13:41:29 +00:00
h.metrics.incrementRequests(h.connectionID)
2017-10-16 11:44:03 +00:00
req, err := http.NewRequest("GET", h.originUrl, h2mux.MuxedStreamReader{MuxedStream: stream})
if err != nil {
2018-02-20 21:13:56 +00:00
Log.WithError(err).Panic("Unexpected error from http.NewRequest")
2017-10-16 11:44:03 +00:00
}
err = H2RequestHeadersToH1Request(stream.Headers, req)
if err != nil {
2018-02-20 21:13:56 +00:00
Log.WithError(err).Error("invalid request received")
2017-10-16 11:44:03 +00:00
}
h.AppendTagHeaders(req)
2018-03-22 15:24:52 +00:00
cfRay := FindCfRayHeader(req)
h.logRequest(req, cfRay)
2018-02-20 21:13:56 +00:00
if websocket.IsWebSocketUpgrade(req) {
conn, response, err := websocket.ClientConnect(req, h.tlsConfig)
if err != nil {
h.logError(stream, err)
} else {
stream.WriteHeaders(H1ResponseToH2Response(response))
defer conn.Close()
websocket.Stream(conn.UnderlyingConn(), stream)
2018-03-22 15:24:52 +00:00
h.metrics.incrementResponses(h.connectionID, "200")
h.logResponse(response, cfRay)
2018-02-20 21:13:56 +00:00
}
2017-10-16 11:44:03 +00:00
} else {
2018-02-20 21:13:56 +00:00
response, err := h.httpClient.RoundTrip(req)
if err != nil {
h.logError(stream, err)
} else {
defer response.Body.Close()
stream.WriteHeaders(H1ResponseToH2Response(response))
io.Copy(stream, response.Body)
h.metrics.incrementResponses(h.connectionID, "200")
2018-03-22 15:24:52 +00:00
h.logResponse(response, cfRay)
2018-02-20 21:13:56 +00:00
}
2017-10-16 11:44:03 +00:00
}
2017-11-28 13:41:29 +00:00
h.metrics.decrementConcurrentRequests(h.connectionID)
2017-10-16 11:44:03 +00:00
return nil
}
2017-11-28 13:41:29 +00:00
2018-02-20 21:13:56 +00:00
func (h *TunnelHandler) logError(stream *h2mux.MuxedStream, err error) {
Log.WithError(err).Error("HTTP request error")
stream.WriteHeaders([]h2mux.Header{{Name: ":status", Value: "502"}})
stream.Write([]byte("502 Bad Gateway"))
h.metrics.incrementResponses(h.connectionID, "502")
}
2018-03-22 15:24:52 +00:00
func (h *TunnelHandler) logRequest(req *http.Request, cfRay string) {
if cfRay != "" {
Log.WithField("CF-RAY", cfRay).Infof("%s %s %s", req.Method, req.URL, req.Proto)
} else {
Log.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)
}
Log.Debugf("Request Headers %+v", req.Header)
}
func (h *TunnelHandler) logResponse(r *http.Response, cfRay string) {
if cfRay != "" {
Log.WithField("CF-RAY", cfRay).Infof("%s", r.Status)
} else {
Log.Infof("%s", r.Status)
}
Log.Debugf("Response Headers %+v", r.Header)
}
func (h *TunnelHandler) UpdateMetrics(connectionID string) {
h.metrics.updateMuxerMetrics(connectionID, h.muxer.Metrics())
2017-11-28 13:41:29 +00:00
}
func uint8ToString(input uint8) string {
return strconv.FormatUint(uint64(input), 10)
}