forwarder

package module
v1.0.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2023 License: MIT, MPL-2.0 Imports: 31 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")}

Functions

func NewHTTPTransport

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

func NewResolver

func NewResolver(cfg *DNSConfig, log 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 ReadURL

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

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

func RedactHostPortUser

func RedactHostPortUser(hpu *HostPortUser) string

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, config, 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 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
	// Timeout is the timeout for DNS queries.
	Timeout time.Duration
}

func DefaultDNSConfig

func DefaultDNSConfig() *DNSConfig

func (*DNSConfig) Validate

func (c *DNSConfig) Validate() error

type HTTPProxy

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

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
	ProxyLocalhost    ProxyLocalhostMode
	UpstreamProxy     *url.URL
	UpstreamProxyFunc ProxyFunc
	RequestModifiers  []martian.RequestModifier
	ResponseModifiers []martian.ResponseModifier
	CloseAfterReply   bool
	RemoveHeaders     []string
}

func DefaultHTTPProxyConfig

func DefaultHTTPProxyConfig() *HTTPProxyConfig

func (*HTTPProxyConfig) Validate

func (c *HTTPProxyConfig) Validate() error

type HTTPServer

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

func NewHTTPServer

func NewHTTPServer(cfg *HTTPServerConfig, h http.Handler, log 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
	Addr              string
	CertFile          string
	KeyFile           string
	ReadTimeout       time.Duration
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	LogHTTPMode       httplog.LoggerMode

	PromNamespace string
	PromRegistry  prometheus.Registerer
	BasicAuth     *url.Userinfo
}

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

	// 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

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

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

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

	// 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

	// 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

	// 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

	// 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

	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 LoggingPACResolver

type LoggingPACResolver struct {
	Resolver PACResolver
	Logger   log.Logger
}

func (*LoggingPACResolver) FindProxyForURL

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

type PACResolver

type PACResolver interface {
	// FindProxyForURL calls FindProxyForURL or FindProxyForURLEx function in the PAC script.
	// The hostname is optional, if empty it will be extracted from URL.
	FindProxyForURL(url *url.URL, hostname string) (string, error)
}

type ProxyFunc

type ProxyFunc func(*http.Request) (*url.URL, error)

type ProxyLocalhostMode

type ProxyLocalhostMode string
const (
	DenyProxyLocalhost   ProxyLocalhostMode = "deny"
	AllowProxyLocalhost  ProxyLocalhostMode = "allow"
	DirectProxyLocalhost ProxyLocalhostMode = "direct"
)

func (ProxyLocalhostMode) String

func (m ProxyLocalhostMode) String() string

func (*ProxyLocalhostMode) UnmarshalText

func (m *ProxyLocalhostMode) UnmarshalText(text []byte) error

type Scheme

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

func (Scheme) String

func (s Scheme) String() string

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
}

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.
utlils

Jump to

Keyboard shortcuts

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