proxy

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2021 License: MIT, Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Binary
	KiB = 1024
	MiB = 1024 * KiB
	GiB = 1024 * MiB
	TiB = 1024 * GiB
	PiB = 1024 * TiB
)

See: http://en.wikipedia.org/wiki/Binary_prefix

View Source
const BufferSize = KiB

BufferSize this is the size of data that is read/written by default.

Variables

View Source
var ErrPortNotAllowed = errors.New("proxy: port not allowed")

ErrPortNotAllowed is returned when opening non whitelisted port.

Functions

func BytesSize

func BytesSize(size float64) string

BytesSize returns a human-readable size in bytes, kibibytes, mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB").

func Copy

func Copy(ctx context.Context, from, to net.Conn) error

Copy starts two goroutines. On that copy from=>to and another that copies to>from from is downstream connection while to is the upstream connection.

func CustomSize

func CustomSize(format string, size float64, base float64, _map []string) string

CustomSize returns a human-readable approximation of a size using custom format.

func ErrIsNetClosed

func ErrIsNetClosed(err error) bool

ErrIsNetClosed returns true if err is an error returned when using a closed network connection

func ListenDTLS

func ListenDTLS(network string, addr *net.UDPAddr) (net.Listener, error)

ListenDTLS implements listener for dtls

func RAMInBytes

func RAMInBytes(size string) (int64, error)

RAMInBytes parses a human-readable string representing an amount of RAM in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and returns the number of bytes, or -1 if the string is unparseable. Units are case-insensitive, and the 'b' suffix is optional.

func UnderlyingConn

func UnderlyingConn(c net.Conn) net.Conn

UnderlyingConn returns c.Conn if c of type *Conn, otherwise it returns c.

func UpdateContext

func UpdateContext(ctx context.Context, fn func(*ContextMeta)) context.Context

UpdateContext applies fn to the Meta that is in ctx and returns a new context if ctx doesn't have Meta yet.

Types

type Addr

type Addr struct {
	Address string
}

type Address

type Address struct {
	//L Local
	L Addr
	// R remote
	R Addr
}

Address data for connection address

type Conn

type Conn struct {
	// HostName is the hostname field that was sent to the request router.
	// In the case of TLS, this is the SNI header, in the case of HTTPHost
	// route, it will be the host header.  In the case of a fixed
	// route, i.e. those created with AddRoute(), this will always be
	// empty. This can be useful in the case where further routing decisions
	// need to be made in the Target implementation.
	HostName string

	// Peeked are the bytes that have been read from Conn for the
	// purposes of route matching, but have not yet been consumed
	// by Read calls. It set to nil by Read when fully consumed.
	Peeked []byte

	// Conn is the underlying connection.
	// It can be type asserted against *net.TCPConn or other types
	// as needed. It should not be read from directly unless
	// Peeked is nil.
	net.Conn
}

Conn is an incoming connection that has had some bytes read from it to determine how to route the connection. The Read method stitches the peeked bytes and unread bytes back together.

func (*Conn) Read

func (c *Conn) Read(p []byte) (n int, err error)

type Context

type Context struct {
	ID int64
}

Context holds information about an a tcp request/response

func NewContext

func NewContext() *Context

type ContextMeta

type ContextMeta struct {
	ID atomic.Int64
	// Downstream
	D TCP
	// Upstream
	U TCP
	// ACME true if we are serving acme challenge
	ACME atomic.Bool
	// Fixed is true if we are serving a fixed target
	Fixed atomic.Bool
	// NoMatch true if we have no matching route
	NoMatch atomic.Bool
	// ServerName SNI or Host of the server serving the request
	ServerName atomic.String
	// RouteName the name of the route if any
	RouteName atomic.String
	// Protocol The protocol which we are serving
	Protocol   atomic.Uint32
	Start, End time.Time
	Speed      SpeedRateConfig
	Rate       Rate
	// Labels these are labels that are attached to the request
	Labels map[string]string
	// contains filtered or unexported fields
}

Meta a lot of details that is passed around with the connection.

func GetContextMeta

func GetContextMeta(ctx context.Context) *ContextMeta

func (*ContextMeta) Complete

func (m *ContextMeta) Complete()

func (*ContextMeta) Emit

func (m *ContextMeta) Emit()

Emit based on m emits various metrics exposed by prometheus

func (*ContextMeta) GetBaseLabels

func (m *ContextMeta) GetBaseLabels(lbs ...map[string]string) prometheus.Labels

func (*ContextMeta) GetLabels

func (m *ContextMeta) GetLabels(lbs ...map[string]string) prometheus.Labels

func (ContextMeta) GetProtocol

func (m ContextMeta) GetProtocol() Protocol

func (ContextMeta) GetRare

func (m ContextMeta) GetRare() RateConfig

GetRare returns rate limiting configuration for this route

func (*ContextMeta) Log

func (m *ContextMeta) Log()

Log write logs about the request

type DialProxy

type DialProxy struct {
	Network string

	// Addr is the TCP address to proxy to.
	Addr string

	// KeepAlivePeriod sets the period between TCP keep alives.
	// If zero, a default is used. To disable, use a negative number.
	// The keep-alive is used for both the client connection and
	KeepAlivePeriod time.Duration

	// DialTimeout optionally specifies a dial timeout.
	// If zero, a default is used.
	// If negative, the timeout is disabled.
	DialTimeout time.Duration

	// DialContext optionally specifies an alternate dial function
	// for TCP targets. If nil, the standard
	// net.Dialer.DialContext method is used.
	DialContext func(ctx context.Context, network, address string) (net.Conn, error)

	// OnDialError optionally specifies an alternate way to handle errors dialing Addr.
	// If nil, the error is logged and src is closed.
	// If non-nil, src is not closed automatically.
	OnDialError func(src net.Conn, dstDialErr error)

	// ProxyProtocolVersion optionally specifies the version of
	// HAProxy's PROXY protocol to use. The PROXY protocol provides
	// connection metadata to the DialProxy target, via a header
	// inserted ahead of the client's traffic. The DialProxy target
	// must explicitly support and expect the PROXY header; there is
	// no graceful downgrade.
	// If zero, no PROXY header is sent. Currently, version 1 is supported.
	ProxyProtocolVersion int
	// MetricsLabels labels included when emitting metrics about the TPC proxying
	// with this Dial
	MetricsLabels map[string]string

	UpstreamSpeed   Speed
	DownstreamSpeed Speed
}

DialProxy implements Target by dialing a new connection to Addr and then proxying data back and forth.

The To func is a shorthand way of creating a DialProxy.

func To

func To(addr string) *DialProxy

To is shorthand way of writing &tlsproxy.DialProxy{Addr: addr}.

func (*DialProxy) HandleConn

func (dp *DialProxy) HandleConn(ctx context.Context, src net.Conn)

HandleConn implements the Target interface.

type Downstream

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

func (*Downstream) ReadTo

func (u *Downstream) ReadTo(dest io.Writer, size int64) (int64, error)

func (*Downstream) Write

func (u *Downstream) Write(b []byte) (int, error)

type Incoming

type Incoming struct {
	*bufio.Reader
}

type Matcher

type Matcher func(ctx context.Context, hostname string) bool

Matcher reports whether hostname matches the Matcher's criteria.

type Options

type Options struct {
	HostPort        string
	ControlHostPort string
	AllowedPOrts    []int
	Labels          map[string]string
	Config          api.Config
}

type Protocol

type Protocol uint
const (
	RawTCP Protocol = iota
	HTTP
	UDP
	Websocket
)

func (Protocol) String

func (p Protocol) String() string

type Proxy

type Proxy struct {

	// ListenFunc optionally specifies an alternate listen
	// function. If nil, net.Dial is used.
	// The provided net is always "tcp".
	ListenFunc func(net, laddr string) (net.Listener, error)
	// contains filtered or unexported fields
}

Proxy is a proxy. Its zero value is a valid proxy that does nothing. Call methods to add routes before calling Start or Run.

The order that routes are added in matters; each is matched in the order registered.

func New

func New(ctx context.Context, opts *Options) *Proxy

func (Proxy) AddAllowACMESearch

func (m Proxy) AddAllowACMESearch(ipPort string)

func (Proxy) AddHTTPHostMatchRoute

func (m Proxy) AddHTTPHostMatchRoute(ipPort string, match Matcher, dest Target)

AddHTTPHostMatchRoute appends a route to the ipPort listener that routes to dest if the incoming HTTP/1.x Host header name is accepted by matcher. If it doesn't match, rule processing continues for any additional routes on ipPort.

The ipPort is any valid net.Listen TCP address.

func (Proxy) AddHTTPHostRoute

func (m Proxy) AddHTTPHostRoute(ipPort, httpHost string, dest Target)

AddHTTPHostRoute appends a route to the ipPort listener that routes to dest if the incoming HTTP/1.x Host header name is httpHost. If it doesn't match, rule processing continues for any additional routes on ipPort.

The ipPort is any valid net.Listen TCP address.

func (Proxy) AddRoute

func (m Proxy) AddRoute(ipPort string, dest Target)

AddRoute appends an always-matching route to the ipPort listener, directing any connection to dest.

This is generally used as either the only rule (for simple TCP proxies), or as the final fallback rule for an ipPort.

The ipPort is any valid net.Listen TCP address.

func (Proxy) AddSNIMatchRoute

func (m Proxy) AddSNIMatchRoute(ipPort string, matcher Matcher, dest Target)

AddSNIMatchRoute appends a route to the ipPort listener that routes to dest if the incoming TLS SNI server name is accepted by matcher. If it doesn't match, rule processing continues for any additional routes on ipPort.

By default, the proxy will route all ACME tls-sni-01 challenges received on ipPort to all SNI dests. You can disable ACME routing with AddStopACMESearch.

The ipPort is any valid net.Listen TCP address.

func (Proxy) AddSNIRoute

func (m Proxy) AddSNIRoute(ipPort, sni string, dest Target)

AddSNIRoute appends a route to the ipPort listener that routes to dest if the incoming TLS SNI server name is sni. If it doesn't match, rule processing continues for any additional routes on ipPort.

By default, the proxy will route all ACME tls-sni-01 challenges received on ipPort to all SNI dests. You can disable ACME routing with AddStopACMESearch.

The ipPort is any valid net.Listen TCP address.

func (Proxy) AddStopACMESearch

func (m Proxy) AddStopACMESearch(ipPort string)

func (*Proxy) Close

func (p *Proxy) Close() error

Close closes all the proxy's self-opened listeners.

func (*Proxy) Configure

func (p *Proxy) Configure(x *api.Config) error

func (*Proxy) GetConfig

func (p *Proxy) GetConfig() (*api.Config, error)

func (*Proxy) RPC

func (p *Proxy) RPC() *Updates

RPC returns rpc server used to dynamically update the state of the proxy

func (*Proxy) Reload

func (p *Proxy) Reload(m configMap) error

func (Proxy) Route

func (m Proxy) Route(r *api.Route)

Route generates configuration based on r

func (*Proxy) Start

func (p *Proxy) Start() (err error)

Start creates a TCP listener for each unique ipPort from the previously created routes and starts the proxy. It returns any error from starting listeners.

If it returns a non-nil error, any successfully opened listeners are closed.

func (*Proxy) TriggerReload

func (p *Proxy) TriggerReload() error

type Rate

type Rate struct {
	By      atomic.Uint32
	Average atomic.Float64
	Burst   atomic.Int64
}

type RateBy

type RateBy uint
const (
	IP RateBy = iota
	Host
)

type RateConfig

type RateConfig struct {
	Route   string
	Key     string
	Average float64
	Burst   int
}

type RateCopy

type RateCopy struct {
	WaitN func(int) error
	net.Conn
	OnWrite func(int)
	OnRead  func(int)
}

func (*RateCopy) Write

func (r *RateCopy) Write(b []byte) (n int, err error)

type ServerInfo

type ServerInfo struct {
	Listener net.Listener
	Proxy    *Proxy
}

ServerInfo general information about the server.

func GetInfo

func GetInfo(ctx context.Context) *ServerInfo

GetInfo returns server information from context

type Speed

type Speed string

Speed is a unit representing amount of bytes per duration eg 120kib/s

func (Speed) Limit

func (s Speed) Limit() (float64, error)

type SpeedRateConfig

type SpeedRateConfig struct {
	// This is the amount of bytes read from the client by the server per second.
	// You can think of this as limit on upload speed, where tt is the server
	// receiving the data so it will use this value to limit how much it will be
	// reading per second
	// You can use this to control upload speeds
	Downstream atomic.Float64

	// This is the amount of bytes read from the proxied(upstream) end point. In this case
	// tt will use this to limit how much data it reads from upstream. You can use
	// this to control download speeds
	Upstream atomic.Float64
}

type TCP

type TCP struct {
	// A socket address
	A Address
	// R bytes read from this socket.
	R atomic.Int64
	// W bytes written to this socket
	W atomic.Int64
}

TCP stats about a tcp socket connection

type Target

type Target interface {
	// HandleConn is called when an incoming connection is
	// matched. After the call to HandleConn, the tcpproxy
	// package never touches the conn again. Implementations are
	// responsible for closing the connection when needed.
	//
	// The concrete type of conn will be of type *Conn if any
	// bytes have been consumed for the purposes of route
	// matching.
	HandleConn(context.Context, net.Conn)
}

Target is what an incoming matched connection is sent to.

type TargetListener

type TargetListener struct {
	Address string // Address is the string reported by TargetListener.Addr().String().
	// contains filtered or unexported fields
}

TargetListener implements both net.Listener and Target. Matched Targets become accepted connections.

func (*TargetListener) Accept

func (tl *TargetListener) Accept() (net.Conn, error)

Accept implements the Accept method in the net.Listener interface.

func (*TargetListener) Addr

func (tl *TargetListener) Addr() net.Addr

Addr returns the listener's Address field as a net.Addr.

func (*TargetListener) Close

func (tl *TargetListener) Close() error

Close stops listening for new connections. All new connections routed to this listener will be closed. Already accepted connections are not closed.

func (*TargetListener) HandleConn

func (tl *TargetListener) HandleConn(ctx context.Context, c net.Conn)

HandleConn implements the Target interface. It blocks until tl is closed or another goroutine has called Accept and received c.

type Updates

type Updates struct {
	api.UnimplementedProxyServer
	OnConfigure func(*api.Config) error
}

func (*Updates) Configure

func (u *Updates) Configure(_ context.Context, x *api.Config) (*api.Response, error)

type Upstream

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

func (*Upstream) ReadTo

func (u *Upstream) ReadTo(dest io.Writer, size int64) (int64, error)

func (*Upstream) Write

func (u *Upstream) Write(b []byte) (int, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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