connection

package
v0.0.0-...-11777db Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 6, 2025 License: Apache-2.0 Imports: 42 Imported by: 1

Documentation

Index

Constants

View Source
const (
	LogFieldConnIndex    = "connIndex"
	MaxGracePeriod       = time.Minute * 3
	MaxConcurrentStreams = math.MaxUint32
)
View Source
const (
	InternalUpgradeHeader     = "Cf-Cloudflared-Proxy-Connection-Upgrade"
	InternalTCPProxySrcHeader = "Cf-Cloudflared-Proxy-Src"
	WebsocketUpgrade          = "websocket"
	ControlStreamUpgrade      = "control-stream"
	ConfigurationUpdate       = "update-configuration"
)

note: these constants are exported so we can reuse them in the edge-side code

View Source
const (
	MetricsNamespace = "cloudflared"
	TunnelSubsystem  = "tunnel"
)
View Source
const (
	LogFieldConnectionID = "connection"
	LogFieldLocation     = "location"
	LogFieldIPAddress    = "ip"
	LogFieldProtocol     = "protocol"
)
View Source
const (
	AvailableProtocolFlagMessage = "" /* 267-byte string literal not displayed */

	AutoSelectFlag = "auto"
	// SRV and TXT record resolution TTL
	ResolveTTL = time.Hour
)
View Source
const (
	// HTTPHeaderKey is used to get or set http headers in QUIC ALPN if the underlying proxy connection type is HTTP.
	HTTPHeaderKey = "HttpHeader"
	// HTTPMethodKey is used to get or set http method in QUIC ALPN if the underlying proxy connection type is HTTP.
	HTTPMethodKey = "HttpMethod"
	// HTTPHostKey is used to get or set http host in QUIC ALPN if the underlying proxy connection type is HTTP.
	HTTPHostKey = "HttpHost"

	QUICMetadataFlowID = "FlowID"
)
View Source
const (
	DuplicateConnectionError = "EDUPCONN"
)

Variables

View Source
var (
	// internal special headers
	RequestUserHeaders  = "cf-cloudflared-request-headers"
	ResponseUserHeaders = "cf-cloudflared-response-headers"
	ResponseMetaHeader  = "cf-cloudflared-response-meta"

	// internal special headers
	CanonicalResponseUserHeaders = http.CanonicalHeaderKey(ResponseUserHeaders)
	CanonicalResponseMetaHeader  = http.CanonicalHeaderKey(ResponseMetaHeader)
)
View Source
var ProtocolList = []Protocol{QUIC, HTTP2}

ProtocolList represents a list of supported protocols for communication with the edge in order of precedence for remote percentage fetcher.

Functions

func DialQuic

func DialQuic(
	ctx context.Context,
	quicConfig *quic.Config,
	tlsConfig *tls.Config,
	edgeAddr netip.AddrPort,
	localAddr net.IP,
	connIndex uint8,
	logger *zerolog.Logger,
) (quic.Connection, error)

func FindCfRayHeader

func FindCfRayHeader(req *http.Request) string

func IsControlResponseHeader

func IsControlResponseHeader(headerName string) bool

IsControlResponseHeader is called in the direction of eyeball <- origin.

func IsLBProbeRequest

func IsLBProbeRequest(req *http.Request) bool

func IsTCPStream

func IsTCPStream(r *http.Request) bool

IsTCPStream discerns if the connection request needs a tcp stream proxy.

func IsWebsocketClientHeader

func IsWebsocketClientHeader(headerName string) bool

isWebsocketClientHeader returns true if the header name is required by the client to upgrade properly

func NewHTTP2RespWriter

func NewHTTP2RespWriter(r *http.Request, w http.ResponseWriter, connType Type, log *zerolog.Logger) (*http2RespWriter, error)

func SerializeHeaders

func SerializeHeaders(h1Headers http.Header) string

Serialize HTTP1.x headers by base64-encoding each header name and value, and then joining them in the format of [key:value;]

Types

type ClassicTunnelProperties

type ClassicTunnelProperties struct {
	Hostname   string
	OriginCert []byte
	// feature-flag to use new edge reconnect tokens
	UseReconnectToken bool
}

type ConfigurationUpdateBody

type ConfigurationUpdateBody struct {
	Version int32             `json:"version"`
	Config  gojson.RawMessage `json:"config"`
}

ConfigurationUpdateBody is the representation followed by the edge to send updates to cloudflared.

type ConnectedFuse

type ConnectedFuse interface {
	Connected()
	IsConnected() bool
}

type ControlStreamHandler

type ControlStreamHandler interface {
	// ServeControlStream handles the control plane of the transport in the current goroutine calling this
	ServeControlStream(ctx context.Context, rw io.ReadWriteCloser, connOptions *tunnelpogs.ConnectionOptions, tunnelConfigGetter TunnelConfigJSONGetter) error
	// IsStopped tells whether the method above has finished
	IsStopped() bool
}

ControlStreamHandler registers connections with origintunneld and initiates graceful shutdown.

func NewControlStream

func NewControlStream(
	observer *Observer,
	connectedFuse ConnectedFuse,
	tunnelProperties *TunnelProperties,
	connIndex uint8,
	edgeAddress net.IP,
	registerClientFunc registerClientFunc,
	registerTimeout time.Duration,
	gracefulShutdownC <-chan struct{},
	gracePeriod time.Duration,
	protocol Protocol,
) ControlStreamHandler

NewControlStream returns a new instance of ControlStreamHandler

type Credentials

type Credentials struct {
	AccountTag   string
	TunnelSecret []byte
	TunnelID     uuid.UUID
	Endpoint     string
}

Credentials are stored in the credentials file and contain all info needed to run a tunnel.

func (*Credentials) Auth

func (c *Credentials) Auth() pogs.TunnelAuth

type DatagramSessionHandler

type DatagramSessionHandler interface {
	Serve(context.Context) error

	pogs.SessionManager
}

DatagramSessionHandler is a service that can serve datagrams for a connection and handle sessions from incoming connection streams.

func NewDatagramV2Connection

func NewDatagramV2Connection(ctx context.Context,
	conn quic.Connection,
	icmpRouter ingress.ICMPRouter,
	index uint8,
	rpcTimeout time.Duration,
	streamWriteTimeout time.Duration,
	flowLimiter cfdflow.Limiter,
	logger *zerolog.Logger,
) DatagramSessionHandler

func NewDatagramV3Connection

func NewDatagramV3Connection(ctx context.Context,
	conn quic.Connection,
	sessionManager cfdquic.SessionManager,
	icmpRouter ingress.ICMPRouter,
	index uint8,
	metrics cfdquic.Metrics,
	logger *zerolog.Logger,
) DatagramSessionHandler

type DupConnRegisterTunnelError

type DupConnRegisterTunnelError struct{}

func (DupConnRegisterTunnelError) Error

type EdgeQuicDialError

type EdgeQuicDialError struct {
	Cause error
}

Dial to edge server with quic failed

func (*EdgeQuicDialError) Error

func (e *EdgeQuicDialError) Error() string

func (*EdgeQuicDialError) Unwrap

func (e *EdgeQuicDialError) Unwrap() error

type Event

type Event struct {
	Index       uint8
	EventType   Status
	Location    string
	Protocol    Protocol
	URL         string
	EdgeAddress net.IP
}

Event is something that happened to a connection, e.g. disconnection or registration.

type EventSink

type EventSink interface {
	OnTunnelEvent(event Event)
}

type EventSinkFunc

type EventSinkFunc func(event Event)

func (EventSinkFunc) OnTunnelEvent

func (f EventSinkFunc) OnTunnelEvent(event Event)

type HTTP2Connection

type HTTP2Connection struct {
	// contains filtered or unexported fields
}

HTTP2Connection represents a net.Conn that uses HTTP2 frames to proxy traffic from the edge to cloudflared on the origin.

func NewHTTP2Connection

func NewHTTP2Connection(
	conn net.Conn,
	orchestrator Orchestrator,
	connOptions *tunnelpogs.ConnectionOptions,
	observer *Observer,
	connIndex uint8,
	controlStreamHandler ControlStreamHandler,
	log *zerolog.Logger,
) *HTTP2Connection

NewHTTP2Connection returns a new instance of HTTP2Connection.

func (*HTTP2Connection) Serve

func (c *HTTP2Connection) Serve(ctx context.Context) error

Serve serves an HTTP2 server that the edge can talk to.

func (*HTTP2Connection) ServeHTTP

func (c *HTTP2Connection) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HTTPHeader

type HTTPHeader struct {
	Name  string
	Value string
}

HTTPHeader is a custom header struct that expects only ever one value for the header. This structure is used to serialize the headers and attach them to the HTTP2 request when proxying.

func DeserializeHeaders

func DeserializeHeaders(serializedHeaders string) ([]HTTPHeader, error)

Deserialize headers serialized by `SerializeHeader`

type HTTPResponseReadWriteAcker

type HTTPResponseReadWriteAcker struct {
	// contains filtered or unexported fields
}

HTTPResponseReadWriteAcker is an HTTP implementation of ReadWriteAcker.

func NewHTTPResponseReadWriterAcker

func NewHTTPResponseReadWriterAcker(w ResponseWriter, flusher http.Flusher, req *http.Request) *HTTPResponseReadWriteAcker

NewHTTPResponseReadWriterAcker returns a new instance of HTTPResponseReadWriteAcker.

func (*HTTPResponseReadWriteAcker) AckConnection

func (h *HTTPResponseReadWriteAcker) AckConnection(tracePropagation string) error

AckConnection acks an HTTP connection by sending a switch protocols status code that enables the caller to upgrade to streams.

func (*HTTPResponseReadWriteAcker) Read

func (h *HTTPResponseReadWriteAcker) Read(p []byte) (int, error)

func (*HTTPResponseReadWriteAcker) Write

func (h *HTTPResponseReadWriteAcker) Write(p []byte) (int, error)

type Observer

type Observer struct {
	// contains filtered or unexported fields
}

func NewObserver

func NewObserver(log, logTransport *zerolog.Logger) *Observer

func (*Observer) RegisterSink

func (o *Observer) RegisterSink(sink EventSink)

func (*Observer) SendDisconnect

func (o *Observer) SendDisconnect(connIndex uint8)

func (*Observer) SendReconnect

func (o *Observer) SendReconnect(connIndex uint8)

func (*Observer) SendURL

func (o *Observer) SendURL(url string)

type Orchestrator

type Orchestrator interface {
	UpdateConfig(version int32, config []byte) *pogs.UpdateConfigurationResponse
	GetConfigJSON() ([]byte, error)
	GetOriginProxy() (OriginProxy, error)
}

type OriginProxy

type OriginProxy interface {
	ProxyHTTP(w ResponseWriter, tr *tracing.TracedHTTPRequest, isWebsocket bool) error
	ProxyTCP(ctx context.Context, rwa ReadWriteAcker, req *TCPRequest) error
}

OriginProxy is how data flows from cloudflared to the origin services running behind it.

type Protocol

type Protocol int64
const (
	// HTTP2 using golang HTTP2 library for edge connections.
	HTTP2 Protocol = iota
	// QUIC using quic-go for edge connections.
	QUIC
)

func (Protocol) String

func (p Protocol) String() string

func (Protocol) TLSSettings

func (p Protocol) TLSSettings() *TLSSettings

type ProtocolSelector

type ProtocolSelector interface {
	Current() Protocol
	Fallback() (Protocol, bool)
}

func NewProtocolSelector

func NewProtocolSelector(
	protocolFlag string,
	accountTag string,
	tunnelTokenProvided bool,
	needPQ bool,
	protocolFetcher edgediscovery.PercentageFetcher,
	resolveTTL time.Duration,
	log *zerolog.Logger,
) (ProtocolSelector, error)

type ReadWriteAcker

type ReadWriteAcker interface {
	io.ReadWriter
	AckConnection(tracePropagation string) error
}

ReadWriteAcker is a readwriter with the ability to Acknowledge to the downstream (edge) that the origin has accepted the connection.

type ResponseWriter

type ResponseWriter interface {
	WriteRespHeaders(status int, header http.Header) error
	AddTrailer(trailerName, trailerValue string)
	http.ResponseWriter
	http.Hijacker
	io.Writer
}

ResponseWriter is the response path for a request back through cloudflared's tunnel.

type ServerRegisterTunnelError

type ServerRegisterTunnelError struct {
	Cause     error
	Permanent bool
}

RegisterTunnel error from server

func (ServerRegisterTunnelError) Error

type Status

type Status int

Status is the status of a connection.

const (
	// Disconnected means the connection to the edge was broken.
	Disconnected Status = iota
	// Connected means the connection to the edge was successfully established.
	Connected
	// Reconnecting means the connection to the edge is being re-established.
	Reconnecting
	// SetURL means this connection's tunnel was given a URL by the edge. Used for quick tunnels.
	SetURL
	// RegisteringTunnel means the non-named tunnel is registering its connection.
	RegisteringTunnel
	// We're unregistering tunnel from the edge in preparation for a disconnect
	Unregistering
)

type TCPRequest

type TCPRequest struct {
	Dest      string
	CFRay     string
	LBProbe   bool
	FlowID    string
	CfTraceID string
	ConnIndex uint8
}

TCPRequest defines the input format needed to perform a TCP proxy.

type TLSSettings

type TLSSettings struct {
	ServerName string
	NextProtos []string
}

type TunnelConfigJSONGetter

type TunnelConfigJSONGetter interface {
	GetConfigJSON() ([]byte, error)
}

type TunnelConnection

type TunnelConnection interface {
	Serve(ctx context.Context) error
}

TunnelConnection represents the connection to the edge. The Serve method is provided to allow clients to handle any errors from the connection encountered during processing of the connection. Cancelling of the context provided to Serve will close the connection.

func NewTunnelConnection

func NewTunnelConnection(
	ctx context.Context,
	conn quic.Connection,
	connIndex uint8,
	orchestrator Orchestrator,
	datagramSessionHandler DatagramSessionHandler,
	controlStreamHandler ControlStreamHandler,
	connOptions *pogs.ConnectionOptions,
	rpcTimeout time.Duration,
	streamWriteTimeout time.Duration,
	gracePeriod time.Duration,
	logger *zerolog.Logger,
) (TunnelConnection, error)

NewTunnelConnection takes a quic.Connection to wrap it for use with cloudflared application logic.

type TunnelProperties

type TunnelProperties struct {
	Credentials    Credentials
	Client         pogs.ClientInfo
	QuickTunnelUrl string
}

type TunnelToken

type TunnelToken struct {
	AccountTag   string    `json:"a"`
	TunnelSecret []byte    `json:"s"`
	TunnelID     uuid.UUID `json:"t"`
	Endpoint     string    `json:"e,omitempty"`
}

TunnelToken are Credentials but encoded with custom fields namings.

func (TunnelToken) Credentials

func (t TunnelToken) Credentials() Credentials

func (TunnelToken) Encode

func (t TunnelToken) Encode() (string, error)

type Type

type Type int

Type indicates the connection type of the connection.

const (
	TypeWebsocket Type = iota
	TypeTCP
	TypeControlStream
	TypeHTTP
	TypeConfiguration
)

func (Type) String

func (t Type) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL