forwarder

package module
v1.0.0-rc0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2022 License: MIT, MPL-2.0 Imports: 38 Imported by: 0

README

Forwarder

Forwarder is HTTP proxy. It can be used to proxy HTTP/HTTPS/HTTP2 requests, Server Sent Events, WebSockets, TCP traffic and more. It supports downstream HTTP(S) and SOCKS5 proxies and basic authentication.

Proxy Auto-Configuration (PAC)

Forwarder implements Proxy Auto-Configuration (PAC) file support. PAC file is a JavaScript file that returns a proxy URL for a given URL. It can be used to implement complex proxy rules.

Forwarder also implements Microsoft's PAC extensions for IPv6. So you can use FindProxyForURL and FindProxyForURLEx functions to implement IPv6-aware proxy rules.

Forwarder can be used as a PAC file server (see pac-server command), or as a PAC file test util (see pac-eval command).

Documentation

Overview

Package forwarder provides a simple forward proxy server. The proxy can be protected with HTTP basic authentication. It can also forward connections to a parent proxy, and authorize connections against that. Both local, and parent credentials can be set via environment variables.

Index

Constants

View Source
const ErrorHeader = "X-Forwarder-Error"

ErrorHeader is the header that is set on error responses with the error message.

Variables

View Source
var ErrProxyLocalhost = denyError{errors.New("localhost proxying is disabled")}
View Source
var NopLogger = nopLogger{} //nolint:gochecknoglobals // nop implementation

NopLogger is a logger that does nothing.

Functions

func NewHTTPTransport

func NewHTTPTransport(cfg *HTTPTransportConfig, r *net.Resolver) *http.Transport

func NewResolver

func NewResolver(cfg *DNSConfig, log Logger) (*net.Resolver, error)

func OpenFileParser

func OpenFileParser(flag int, perm, dirPerm os.FileMode) func(val string) (*os.File, error)

OpenFileParser returns a parser that calls os.OpenFile. If dirPerm is set it will create the directory if it does not exist. For empty path the parser returns nil file and nil error.

func ParseDNSAddress

func ParseDNSAddress(val string) (*url.URL, error)

ParseDNSAddress parses a DNS URL or IP address. It supports IP only or full URL. Hostname is not allowed. Examples: `udp://1.1.1.1:53`, `1.1.1.1`.

Requirements: - (Optional) protocol: udp, tcp (default udp) - Only IP not a hostname. - (Optional) port in a valid range: 1 - 65535 (default 53). - No username and password. - No path, query, and fragment.

func ParseProxyURL

func ParseProxyURL(val string) (*url.URL, error)

ParseProxyURL parser a Proxy URL

Requirements: - Protocol: http, https, socks5, socks, quic. - Hostname min 4 chars. - Port in a valid range: 1 - 65535. - (Optional) username and password.

func ParseUserInfo

func ParseUserInfo(val string) (*url.Userinfo, error)

ParseUserInfo parses a user:password string into *url.Userinfo. Username and password cannot be empty.

func ReadHostsFile

func ReadHostsFile() (map[string]net.IP, error)

ReadHostsFile reads the /etc/hosts file and returns a map of hostnames to IP addresses. If the file does not exist, a nil map is returned.

func ReadURL

func ReadURL(u *url.URL, rt http.RoundTripper) (string, error)

ReadURL can read a local file, http or https URL or stdin.

Types

type APIHandler

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

APIHandler serves API endpoints. It provides health and readiness endpoints prometheus metrics, and pprof debug endpoints.

func NewAPIHandler

func NewAPIHandler(r prometheus.Gatherer, s server, pac string) *APIHandler

func (*APIHandler) ServeHTTP

func (h *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type CredentialsMatcher

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

func NewCredentialsMatcher

func NewCredentialsMatcher(credentials []*HostPortUser, log Logger) (*CredentialsMatcher, error)

func (*CredentialsMatcher) Match

func (m *CredentialsMatcher) Match(hostport string) *url.Userinfo

Match `hostport` to one of the configured input. Priority is exact Match, then host, then port, then global wildcard.

func (*CredentialsMatcher) MatchURL

func (m *CredentialsMatcher) MatchURL(u *url.URL) *url.Userinfo

MatchURL adds standard http and https ports if they are missing in URL and calls Match function.

type DNSConfig

type DNSConfig struct {
	// Servers is a list of DNS servers to use, ex. udp://1.1.1.1:53.
	// Requirements:
	// - Known schemes: udp, tcp
	// - IP ONLY.
	// - Port in a valid range: 1 - 65535.
	Servers []*url.URL `json:"servers"`
	// Timeout is the timeout for DNS queries.
	Timeout time.Duration `json:"timeout"`
}

func DefaultDNSConfig

func DefaultDNSConfig() *DNSConfig

func (*DNSConfig) Validate

func (c *DNSConfig) Validate() error

type HTTPProxy

type HTTPProxy struct {
	TLSConfig *tls.Config
	Listener  net.Listener
	// contains filtered or unexported fields
}

func NewHTTPProxy

func NewHTTPProxy(cfg *HTTPProxyConfig, pr PACResolver, cm *CredentialsMatcher, t *http.Transport, log Logger) (*HTTPProxy, error)

func (*HTTPProxy) Addr

func (hp *HTTPProxy) Addr() string

Addr returns the address the server is listening on or an empty string if the server is not running.

func (*HTTPProxy) Run

func (hp *HTTPProxy) Run(ctx context.Context) error

type HTTPProxyConfig

type HTTPProxyConfig struct {
	HTTPServerConfig
	UpstreamProxy  *url.URL `json:"upstream_proxy_uri"`
	ProxyLocalhost bool     `json:"proxy_localhost"`
}

func DefaultHTTPProxyConfig

func DefaultHTTPProxyConfig() *HTTPProxyConfig

func (*HTTPProxyConfig) Validate

func (c *HTTPProxyConfig) Validate() error

type HTTPServer

type HTTPServer struct {
	Listener net.Listener
	// contains filtered or unexported fields
}

func NewHTTPServer

func NewHTTPServer(cfg *HTTPServerConfig, h http.Handler, log Logger) (*HTTPServer, error)

func (*HTTPServer) Addr

func (hs *HTTPServer) Addr() string

Addr returns the address the server is listening on or an empty string if the server is not running.

func (*HTTPServer) Run

func (hs *HTTPServer) Run(ctx context.Context) error

type HTTPServerConfig

type HTTPServerConfig struct {
	Protocol        Scheme        `json:"protocol"`
	Addr            string        `json:"addr"`
	CertFile        string        `json:"cert_file"`
	KeyFile         string        `json:"key_file"`
	ReadTimeout     time.Duration `json:"read_timeout"`
	LogHTTPRequests bool          `json:"log_http_requests"`

	PromNamespace string                `json:"prom_namespace"`
	PromRegistry  prometheus.Registerer `json:"prom_registry"`
	BasicAuth     *url.Userinfo         `json:"basic_auth"`
}

func DefaultHTTPServerConfig

func DefaultHTTPServerConfig() *HTTPServerConfig

func (*HTTPServerConfig) Validate

func (c *HTTPServerConfig) Validate() error

type HTTPTransportConfig

type HTTPTransportConfig struct {
	// DialTimeout is the maximum amount of time a dial will wait for
	// a connect to complete.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout. For instance, TCP timeouts are
	// often around 3 minutes.
	DialTimeout time.Duration `json:"dial_timeout"`

	// KeepAlive specifies the interval between keep-alive
	// probes for an active network connection.
	// If zero, keep-alive probes are sent with a default value
	// (currently 15 seconds), if supported by the protocol and operating
	// system. Network protocols or operating systems that do
	// not support keep-alives ignore this field.
	// If negative, keep-alive probes are disabled.
	KeepAlive time.Duration `json:"keep_alive"`

	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout time.Duration `json:"tls_handshake_timeout"`

	// MaxIdleConns controls the maximum number of idle (keep-alive)
	// connections across all hosts. Zero means no limit.
	MaxIdleConns int `json:"max_idle_conns"`

	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host. If zero,
	// DefaultMaxIdleConnsPerHost is used.
	MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`

	// MaxConnsPerHost optionally limits the total number of
	// connections per host, including connections in the dialing,
	// active, and idle states. On limit violation, dials will block.
	//
	// Zero means no limit.
	MaxConnsPerHost int `json:"max_conns_per_host"`

	// IdleConnTimeout is the maximum amount of time an idle
	// (keep-alive) connection will remain idle before closing
	// itself.
	// Zero means no limit.
	IdleConnTimeout time.Duration `json:"idle_conn_timeout"`

	// ResponseHeaderTimeout, if non-zero, specifies the amount of
	// time to wait for a server's response headers after fully
	// writing the request (including its body, if any). This
	// time does not include the time to read the response body.
	ResponseHeaderTimeout time.Duration `json:"response_header_timeout"`

	// ExpectContinueTimeout, if non-zero, specifies the amount of
	// time to wait for a server's first response headers after fully
	// writing the request headers if the request has an
	// "Expect: 100-continue" header. Zero means no timeout and
	// causes the body to be sent immediately, without
	// waiting for the server to approve.
	// This time does not include the time to send the request header.
	ExpectContinueTimeout time.Duration `json:"expect_continue_timeout"`

	TLSConfig
}

func DefaultHTTPTransportConfig

func DefaultHTTPTransportConfig() *HTTPTransportConfig

type HostPortUser

type HostPortUser struct {
	Host string
	Port string
	*url.Userinfo
}

func ParseHostPortUser

func ParseHostPortUser(val string) (*HostPortUser, error)

ParseHostPortUser parses a user:password@host:port string into HostUser. User and password cannot be empty.

func (*HostPortUser) Validate

func (hpu *HostPortUser) Validate() error

type Logger

type Logger interface {
	Errorf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Debugf(format string, args ...interface{})
}

Logger is the logger used by the forwarder package.

type LoggingPACResolver

type LoggingPACResolver struct {
	Resolver PACResolver
	Logger   Logger
}

func (*LoggingPACResolver) FindProxyForURL

func (r *LoggingPACResolver) FindProxyForURL(u *url.URL, hostname string) (string, error)

type PACResolver

type PACResolver interface {
	FindProxyForURL(url *url.URL, hostname string) (string, error)
}

type Scheme

type Scheme string
const (
	HTTPScheme  Scheme = "http"
	HTTPSScheme Scheme = "https"
	HTTP2Scheme Scheme = "h2"
)

func (Scheme) String

func (s Scheme) String() string

type SelfSignedCert

type SelfSignedCert struct {
	Hosts        []string
	Organization []string
	ValidFrom    time.Time
	ValidFor     time.Duration
	IsCA         bool
	RsaBits      int
	EcdsaCurve   string
	Ed25519Key   bool
}

SelfSignedCert specifies a self-signed certificate to be generated.

func RSASelfSignedCert

func RSASelfSignedCert() *SelfSignedCert

func (*SelfSignedCert) Gen

func (c *SelfSignedCert) Gen() (tls.Certificate, error)

Gen generates a self-signed certificate, the implementation is based on https://golang.org/src/crypto/tls/generate_cert.go.

type TLSConfig

type TLSConfig struct {
	// InsecureSkipVerify controls whether a client verifies the server's
	// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
	// accepts any certificate presented by the server and any host name in that
	// certificate. In this mode, TLS is susceptible to machine-in-the-middle
	// attacks unless custom verification is used. This should be used only for
	// testing or in combination with VerifyConnection or VerifyPeerCertificate.
	InsecureSkipVerify bool `json:"insecure_skip_verify"`
}

Directories

Path Synopsis
cmd
forwarder command
e2e module
internal
log
Package pac provides a PAC file parser and evaluator.
Package pac provides a PAC file parser and evaluator.

Jump to

Keyboard shortcuts

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