Documentation
¶
Overview ¶
Package portmux serves several protocols on one listening port by sniffing the first bytes of each connection and routing it to the listener or handler of a route.
The package keeps four groups:
- Mux and routes: New creates a Mux, Serve runs it on any number of listeners and ServeConn routes a connection obtained elsewhere. Every route is a net.Listener whose Accept returns a *Conn, or passes its connections to a Handler. Routes have a priority and an optional name, and can be added, changed, paused and removed while serving, alone or atomically with Batch. Entry names a group of listeners and RouteConfig.Entries the entries a route serves, so ports and services are set up apart. Reject routes close what they match, for block lists; a fallback route takes what no route matched; a resolver route lets your code choose the route from everything known about the connection, and ResolveHosts and ResolveDomain do so by name through a hostmatch.Map. MaxConns limits the open connections of a route. Snapshot shows the listeners, routes and counters, Bans the banned clients; SetOptions changes limits and timeouts while serving; Shutdown and Close stop the Mux.
- Matchers: Prefix, Regexp, HTTP1, HTTP2, TLS, Domain, HTTP2Preface, SSH, SOCKS4, SOCKS5, PostgreSQL, MQTT, RDP, OpenVPN, XMPP and DNS look at the bytes; AnyBytes takes any client that sent a byte, Silent routes clients that wait for the server and Always takes every connection unread; RemoteIP, LocalIP, their changing forms RemoteIPFunc and LocalIPFunc, and LocalPort look at the addresses; And, Or and Not combine them in any nesting, and MatcherFunc adds your own. HTTP1 and HTTP2 take the filters Host, HostRegexp, Path, PathPrefix, PathRegexp, Method, Header, HeaderRegexp, Query and WebSocket, and TLS takes SNI, SNIRegexp, ALPN and MinTLSVersion, and the fingerprint filters of package fingerprint; AllOf, AnyOf and NoneOf combine the filters of one protocol. Matchers and filters describe themselves in the text that ParseMatcher reads, so the matchers of routes can be kept as text, next to the other settings of their RouteConfig.
- Delivered connections: Conn replays the sniffed bytes and carries the parsed ClientHello, HTTP/1 and h2c request and PROXY header, what your matchers stored with Input.SetValue, its entry and the matching Route. Peek sniffs one connection without a Mux, and NewInput runs matchers on bytes of your choice.
- Options: timeouts, buffer limits, limits of the connections being matched with eviction of the oldest undecided one, rate limits per client and per listener, bans of clients whose connections keep failing, a queue limit per route, an observer of every connection, and a PROXY protocol v1/v2 policy per entry and peer. They can change while serving, most of them can be set for one entry alone with Entry.SetOptions, and Config reads them back.
The parsers and sets work on their own in packages that import little: hostmatch matches host names, ipmatch IP addresses, tlshello parses TLS ClientHellos, httphead HTTP/1.x and h2c request heads, and fingerprint computes JA4 and JA3. PROXY protocol headers are parsed with github.com/djylb/netx/proxyproto.
Routes are tried by priority and then in the order they were added; while a route needs more bytes, the routes after it wait. Matchers run before the first byte and after every read, share one incremental parse per connection, and return NeedMore until they can decide.
Example ¶
Serve a custom protocol, an admin site and a public site over TLS, an HTTP redirect and SSH clients that wait for the server, on one port.
package main
import (
"crypto/tls"
"io"
"log"
"net"
"net/http"
"time"
"github.com/djylb/portmux"
)
func main() {
ln, err := net.Listen("tcp", ":8443")
if err != nil {
log.Fatal(err)
}
m := portmux.New()
agents := m.Listen(portmux.Prefix("AGENT/1\n"))
admin := m.Listen(portmux.TLS(portmux.SNI("admin.example.com")))
site := m.Listen(portmux.TLS())
redirect := m.Listen(portmux.HTTP1())
ssh := m.Listen(portmux.SSH(), portmux.Silent(2*time.Second))
go serveAgents(agents)
go serveAgents(ssh)
go func() { _ = http.Serve(tls.NewListener(admin, &tls.Config{ /* certificates */ }), adminHandler()) }()
go func() { _ = http.Serve(tls.NewListener(site, &tls.Config{ /* certificates */ }), publicHandler()) }()
go func() {
_ = http.Serve(redirect, http.RedirectHandler("https://example.com/", http.StatusMovedPermanently))
}()
log.Fatal(m.Serve(ln))
}
func serveAgents(l net.Listener) {
for {
c, err := l.Accept()
if err != nil {
return
}
go func() {
defer func() { _ = c.Close() }()
_, _ = io.Copy(c, c)
}()
}
}
func adminHandler() http.Handler { return http.NotFoundHandler() }
func publicHandler() http.Handler { return http.NotFoundHandler() }
Output:
Index ¶
- Constants
- Variables
- func FormatMatcher(m Matcher) (string, error)
- func TrustPeers(prefixes ...netip.Prefix) func(entry string, peer, local net.Addr) proxyproto.Policy
- type Ban
- type Batch
- func (b *Batch) Add(cfg RouteConfig) (*Route, error)
- func (b *Batch) Remove(r *Route) error
- func (b *Batch) Route(name string) *Route
- func (b *Batch) Routes() []*Route
- func (b *Batch) SetDispatchTimeout(r *Route, d time.Duration) error
- func (b *Batch) SetEntries(r *Route, entries ...string) error
- func (b *Batch) SetHandler(r *Route, handler func(*Conn)) error
- func (b *Batch) SetMatchers(r *Route, matchers ...Matcher) error
- func (b *Batch) SetMaxConns(r *Route, n int) error
- func (b *Batch) SetMaxQueued(r *Route, n int) error
- func (b *Batch) SetPriority(r *Route, priority int) error
- func (b *Batch) SetResolve(r *Route, resolve ResolveFunc) error
- func (b *Batch) Upsert(cfg RouteConfig) (*Route, error)
- type Config
- type Conn
- func (c *Conn) ClientHello() *tlshello.Hello
- func (c *Conn) Close() error
- func (c *Conn) CloseRead() error
- func (c *Conn) CloseWrite() error
- func (c *Conn) Entry() string
- func (c *Conn) HTTP2Request() *httphead.Request
- func (c *Conn) HTTPRequest() *httphead.Request
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) NetConn() net.Conn
- func (c *Conn) ProxyHeader() *proxyproto.Header
- func (c *Conn) Read(p []byte) (n int, err error)
- func (c *Conn) ReadFrom(r io.Reader) (n int64, err error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) RequestedName() string
- func (c *Conn) Route() *Route
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) Unread() []byte
- func (c *Conn) Value(key any) any
- func (c *Conn) Write(p []byte) (n int, err error)
- func (c *Conn) WriteTo(w io.Writer) (n int64, err error)
- type Entry
- type EntryOption
- func WithBanPerClient(failures int, window, d time.Duration) EntryOption
- func WithDispatchTimeout(d time.Duration) EntryOption
- func WithMaxPendingPerClient(n int) EntryOption
- func WithMaxQueued(n int) EntryOption
- func WithRateLimitPerClient(perSecond float64, burst int) EntryOption
- func WithRateLimitPerListener(perSecond float64, burst int) EntryOption
- type Event
- type Filter
- type FilterFunc
- type FullPolicy
- type HTTPFilter
- func Header(name string, tokens ...string) HTTPFilter
- func HeaderRegexp(name string, re *regexp.Regexp) HTTPFilter
- func Host(patterns ...string) HTTPFilter
- func HostRegexp(re *regexp.Regexp) HTTPFilter
- func Method(methods ...string) HTTPFilter
- func Path(paths ...string) HTTPFilter
- func PathPrefix(prefixes ...string) HTTPFilter
- func PathRegexp(re *regexp.Regexp) HTTPFilter
- func Query(name string, values ...string) HTTPFilter
- func WebSocket() HTTPFilter
- type HTTPFilterFunc
- type Input
- func (in *Input) Bytes() []byte
- func (in *Input) ClientHello() (*tlshello.Hello, Result)
- func (in *Input) Elapsed() time.Duration
- func (in *Input) Entry() string
- func (in *Input) Final() bool
- func (in *Input) HTTP2Request() (*httphead.Request, Result)
- func (in *Input) HTTPRequest() (*httphead.Request, Result)
- func (in *Input) LocalAddr() net.Addr
- func (in *Input) PeerAddr() net.Addr
- func (in *Input) ProxyHeader() *proxyproto.Header
- func (in *Input) RDPCookie() (string, Result)
- func (in *Input) RemoteAddr() net.Addr
- func (in *Input) RequestedName() (string, Result)
- func (in *Input) SetBytes(data []byte, final bool)
- func (in *Input) SetEntry(name string)
- func (in *Input) SetRequestedName(name string)
- func (in *Input) SetValue(key, value any)
- func (in *Input) Value(key any) any
- type ListenerInfo
- type Matcher
- func Always() Matcher
- func And(matchers ...Matcher) Matcher
- func AnyBytes() Matcher
- func DNS() Matcher
- func Domain(patterns ...string) Matcher
- func HTTP1(filters ...HTTPFilter) Matcher
- func HTTP2(filters ...HTTPFilter) Matcher
- func HTTP2Preface() Matcher
- func LocalIP(prefixes ...netip.Prefix) Matcher
- func LocalIPFunc(contains func(netip.Addr) bool) Matcher
- func LocalPort(ports ...uint16) Matcher
- func MQTT() Matcher
- func Named(name string, m Matcher) Matcher
- func Not(m Matcher) Matcher
- func OpenVPN() Matcher
- func Or(matchers ...Matcher) Matcher
- func ParseMatcher(text string, names *Names) (m Matcher, err error)
- func PostgreSQL() Matcher
- func Prefix(prefixes ...string) Matcher
- func RDP() Matcher
- func Regexp(re *regexp.Regexp, n int) Matcher
- func RemoteIP(prefixes ...netip.Prefix) Matcher
- func RemoteIPFunc(contains func(netip.Addr) bool) Matcher
- func SOCKS4() Matcher
- func SOCKS5() Matcher
- func SSH() Matcher
- func Silent(d time.Duration) Matcher
- func TLS(filters ...TLSFilter) Matcher
- func XMPP() Matcher
- type MatcherFunc
- type Mux
- func (m *Mux) Add(cfg RouteConfig) (*Route, error)
- func (m *Mux) Ban(client netip.Addr, d time.Duration)
- func (m *Mux) BanPrefix(network netip.Prefix, d time.Duration)
- func (m *Mux) Bans() []Ban
- func (m *Mux) Batch(fn func(b *Batch) error) error
- func (m *Mux) Close() error
- func (m *Mux) Config() Config
- func (m *Mux) Entries() []string
- func (m *Mux) Entry(name string) *Entry
- func (m *Mux) LastObserverPanic() *PanicError
- func (m *Mux) Listen(matchers ...Matcher) *Route
- func (m *Mux) Route(name string) *Route
- func (m *Mux) Routes() []*Route
- func (m *Mux) Serve(ln net.Listener) error
- func (m *Mux) ServeConn(c net.Conn) error
- func (m *Mux) SetOptions(opts ...Option)
- func (m *Mux) Shutdown(ctx context.Context) error
- func (m *Mux) Snapshot() Snapshot
- func (m *Mux) Stats() Stats
- func (m *Mux) Unban(client netip.Addr) bool
- func (m *Mux) UnbanPrefix(network netip.Prefix) bool
- func (m *Mux) Upsert(cfg RouteConfig) (*Route, error)
- type Names
- type Option
- type PanicError
- type ParseError
- type PeekOption
- type Peeker
- type ResolveFunc
- type Result
- type Route
- func (r *Route) Accept() (net.Conn, error)
- func (r *Route) AcceptConn() (*Conn, error)
- func (r *Route) Addr() net.Addr
- func (r *Route) Close() error
- func (r *Route) Entries() []string
- func (r *Route) Fallback() bool
- func (r *Route) Info() RouteInfo
- func (r *Route) Matched() uint64
- func (r *Route) Matchers() []Matcher
- func (r *Route) MaxConns() int
- func (r *Route) Name() string
- func (r *Route) Priority() int
- func (r *Route) Reject() bool
- func (r *Route) SetDispatchTimeout(d time.Duration) error
- func (r *Route) SetEntries(entries ...string) error
- func (r *Route) SetHandler(handler func(*Conn)) error
- func (r *Route) SetMatchers(matchers ...Matcher) error
- func (r *Route) SetMaxConns(n int) error
- func (r *Route) SetMaxQueued(n int) error
- func (r *Route) SetPriority(priority int) error
- func (r *Route) SetResolve(resolve ResolveFunc) error
- type RouteConfig
- type RouteInfo
- type Silencer
- type Snapshot
- type SniffOption
- type Stats
- type TLSFilter
- type TLSFilterFunc
Examples ¶
Constants ¶
const ( DefaultSniffTimeout = 10 * time.Second DefaultDispatchTimeout = 5 * time.Second DefaultMaxSniffBytes = 16 << 10 DefaultMaxPending = 4096 DefaultMaxQueued = 1024 // DefaultMaxClientRecords is the number of clients that each table of // WithClientRecords holds unless set. DefaultMaxClientRecords = 1 << 16 // MaxSniffBytesLimit is the largest value WithMaxSniffBytes accepts. MaxSniffBytesLimit = 16 << 20 )
Defaults applied by New when the matching option is not given.
Variables ¶
var ( // ErrNoMatch is reported for a connection that no route accepted, and // returned by Peek when its matchers ruled the connection out. ErrNoMatch = errors.New("portmux: no match for the connection") // ErrSniffTimeout is reported for a connection that did not send enough // bytes to be routed before the sniff timeout. The reported error also // wraps the read error. ErrSniffTimeout = errors.New("portmux: sniff timeout") // ErrDispatchTimeout is reported for a matched connection that its route // did not accept before the dispatch timeout. ErrDispatchTimeout = errors.New("portmux: dispatch timeout") // ErrPendingLimit is reported for a connection closed because its client // reached the WithMaxPendingPerClient limit. ErrPendingLimit = errors.New("portmux: too many pending connections from one client") // ErrRateLimited is reported for a connection closed because its client // or its listener took connections faster than WithRateLimitPerClient or // WithRateLimitPerListener allows. ErrRateLimited = errors.New("portmux: connection rate exceeded") // ErrBanned is reported for a connection closed because its client is // banned; see WithBanPerClient and Mux.Ban. ErrBanned = errors.New("portmux: client is banned") // ErrEvicted is reported for an undecided connection closed to make room // for a new one when the WithMaxPending limit was reached. ErrEvicted = errors.New("portmux: evicted to make room for new connections") // ErrQueueFull is reported for a matched connection closed because its // route already had WithMaxQueued connections waiting for Accept, // which tells that its server does not keep up. ErrQueueFull = errors.New("portmux: route has too many connections waiting") // ErrConnLimit is reported for a matched connection closed because its // route already had RouteConfig.MaxConns connections open. ErrConnLimit = errors.New("portmux: route has too many open connections") // ErrRouteClosed is reported for a connection that a resolver sent to a // route that was closed or removed. ErrRouteClosed = errors.New("portmux: resolved to a closed route") // ErrRefused is reported for a connection closed by a reject route. ErrRefused = errors.New("portmux: refused by a reject route") // ErrEntryMismatch is reported for a connection that a resolver sent to // a route limited to other entries; see RouteConfig.Entries. ErrEntryMismatch = errors.New("portmux: resolved to a route of another entry") // ErrDuplicateName is returned when a route name is already in use. ErrDuplicateName = errors.New("portmux: duplicate route name") // ErrInvalidRoute is wrapped by the errors that Add, Batch and the // setters of a Route return for a configuration that is not valid, such // as a fallback route with matchers, or for a route of another Mux; and // by the error reported for a connection that a resolver sent to a // route of another Mux. ErrInvalidRoute = errors.New("portmux: invalid route") )
Functions ¶
func FormatMatcher ¶
FormatMatcher returns reloadable text for a rule composed entirely of built-in matchers and filters, within the limits of ParseMatcher. For custom rules, persist the original configuration text and parse it with the same Names. Named descriptions are for display.
func TrustPeers ¶
func TrustPeers(prefixes ...netip.Prefix) func(entry string, peer, local net.Addr) proxyproto.Policy
TrustPeers returns a policy for WithProxyProtocol under which the peers in prefixes, such as the addresses of a load balancer, must send a PROXY header on every entry, and other peers are served as they are, as proxyproto.TrustPrefixes reads the prefixes. A health check of the peer that sends bytes without a header then fails, though without banning the peer; let health checks send nothing, or write a policy of your own that makes headers optional, as it also may to tell entries apart.
Types ¶
type Ban ¶
type Ban struct {
// Client is the banned network, of the prefix lengths of
// WithClientPrefix when it was banned.
Client netip.Prefix
// Until is when the ban ends.
Until time.Time
}
Ban is a banned client.
type Batch ¶
type Batch struct {
// contains filtered or unexported fields
}
Batch collects route changes that a Mux applies together: a connection is matched either against the routes before every change or after all of them. A Batch is only valid during the function passed to Mux.Batch.
func (*Batch) Route ¶
Route returns the route with the given name, including changes made in this batch, or nil.
func (*Batch) Routes ¶
Routes returns the routes in the order they would be matched if the batch were applied now, fallback routes last. It previews where a new route lands; return an error from the batch function to drop the changes.
func (*Batch) SetDispatchTimeout ¶
SetDispatchTimeout changes the dispatch timeout of r; see RouteConfig.DispatchTimeout.
func (*Batch) SetEntries ¶
SetEntries limits r to connections of the entries, or lets it apply to every entry when none are given.
func (*Batch) SetHandler ¶
SetHandler changes the handler of r, or turns r into a route that delivers to Accept with nil; see RouteConfig.Handler. Connections that already wait for Accept stay there.
func (*Batch) SetMatchers ¶
SetMatchers replaces the matchers of r.
func (*Batch) SetMaxConns ¶
SetMaxConns changes the limit of open connections of r; see RouteConfig.MaxConns. Open connections over a lowered limit stay open.
func (*Batch) SetMaxQueued ¶
SetMaxQueued changes the limit of queued connections of r; see RouteConfig.MaxQueued.
func (*Batch) SetPriority ¶
SetPriority changes the priority of r.
func (*Batch) SetResolve ¶
func (b *Batch) SetResolve(r *Route, resolve ResolveFunc) error
SetResolve changes the resolver of r, or removes it with nil; see RouteConfig.Resolve.
func (*Batch) Upsert ¶
func (b *Batch) Upsert(cfg RouteConfig) (*Route, error)
Upsert adds the route named cfg.Name, or changes the route of that name to cfg, keeping the route and its listener, so that a server in its Accept goes on serving it: reloading a configuration route by route closes no listener of a route that stays. A route whose Reject or Fallback changes is a different kind of route: Upsert replaces it, closing the old one, whose connections waiting for Accept are matched again. cfg.Name must not be empty.
type Config ¶
type Config struct {
SniffTimeout time.Duration
DispatchTimeout time.Duration
MaxSniffBytes int
MaxPending int
MaxPendingPerClient int
MaxQueued int
// RateLimitPerClient and RateBurstPerClient are the arguments of
// WithRateLimitPerClient, and the next two those of WithRateLimitPerListener.
RateLimitPerClient float64
RateBurstPerClient int
RateLimitPerListener float64
RateBurstPerListener int
// BanFailures, BanWindow and BanDuration are the arguments of
// WithBanPerClient.
BanFailures int
BanWindow time.Duration
BanDuration time.Duration
// ClientPrefix4 and ClientPrefix6 are the arguments of WithClientPrefix.
ClientPrefix4 int
ClientPrefix6 int
// MaxClientRecords and ClientRecordsFull are the arguments of
// WithClientRecords.
MaxClientRecords int
ClientRecordsFull FullPolicy
// Observer and ProxyProtocol report whether WithObserver and
// WithProxyProtocol set a function.
Observer bool
ProxyProtocol bool
// CloseEvents is the argument of WithCloseEvents.
CloseEvents bool
}
Config reports the settings of a Mux, or those that apply to the connections of one entry, as the options set them; see Mux.Config and Entry.Config.
func (Config) EntryOptions ¶
func (c Config) EntryOptions() []EntryOption
EntryOptions returns the options that set the settings of c that an entry can have, for Entry.SetOptions, so that settings read with Config, stored or changed, can be set again. Every setting then becomes the entry's own, with the values of c: the entry no longer follows later changes of the Mux's options, and its rate limit and ban counts become its own, as Entry.SetOptions describes; pick the options to set for less.
func (Config) Options ¶
Options returns the options that set the settings of c, for New and Mux.SetOptions: those of EntryOptions, WithMaxPending, WithClientPrefix, WithClientRecords and WithCloseEvents. The functions of WithObserver and WithProxyProtocol, which Config does not hold, are not among them, so SetOptions keeps them.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a connection with the bytes that were read while matching it placed back in front of its stream: routes and Peek return one.
Reads first return those bytes and then continue with the client's stream. When a PROXY protocol header was parsed, RemoteAddr and LocalAddr report its addresses.
func Peek ¶
Peek reads the first bytes of c until m matches or rules the connection out, without consuming them, as a Mux does for its routes. It needs no Mux, so a server that already holds a connection can, for example, read its SNI before deciding how to serve it.
Peek returns c wrapped in a Conn that replays the bytes read and carries what was parsed: the ClientHello, the HTTP request head and the PROXY header. The Conn is returned whatever the outcome, and Peek never closes c, so the caller can still serve the connection or close the Conn. The error is nil when m matched, ErrNoMatch when it ruled the connection out, and otherwise what stopped reading, such as ErrSniffTimeout or io.EOF.
The options are those of the sniffing: WithSniffTimeout, WithMaxSniffBytes and WithProxyProtocol. Silent works as in a Mux. Peek sets read deadlines on c while reading and clears them before it returns.
Example ¶
Read the SNI of a connection without a Mux, then serve it with the TLS configuration for that name.
package main
import (
"crypto/tls"
"io"
"log"
"net"
"time"
"github.com/djylb/portmux"
)
func main() {
ln, err := net.Listen("tcp", ":443")
if err != nil {
log.Fatal(err)
}
configs := map[string]*tls.Config{ /* one per name */ }
for {
c, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
go func() {
conn, err := portmux.Peek(c, portmux.TLS(), portmux.WithSniffTimeout(5*time.Second))
if err != nil {
_ = conn.Close()
return
}
// The name lowercased, as the configs are keyed.
config, ok := configs[conn.ClientHello().Name().String()]
if !ok {
_ = conn.Close()
return
}
// The handshake reads the ClientHello again from conn.
tc := tls.Server(conn, config)
defer func() { _ = tc.Close() }()
_, _ = io.Copy(tc, tc)
}()
}
}
Output:
func PeekAny ¶
PeekAny is Peek for several matchers, tried in order as the routes of a Mux are: it returns the index of the first that matches, or -1 with an error, so that a server learns which protocol the client speaks, as in PeekAny(c, []Matcher{TLS(), HTTP1(), SSH()}). A matcher that still needs bytes holds back the later ones, as a route does, and Silent among them works as in a Mux. PeekAny panics without a connection, without matchers or on a nil one, as Peek does.
func (*Conn) ClientHello ¶
ClientHello returns the TLS ClientHello parsed while matching, or nil when none was parsed. It is always set for routes that matched with TLS.
func (*Conn) Close ¶
Close closes the connection. The first Close ends the connection's count as open and, with WithCloseEvents, reports it to the observer.
func (*Conn) CloseRead ¶
CloseRead shuts down the reading side when the underlying connection supports it, and returns errors.ErrUnsupported otherwise.
func (*Conn) CloseWrite ¶
CloseWrite shuts down the writing side when the underlying connection supports it, and returns errors.ErrUnsupported otherwise.
func (*Conn) Entry ¶
Entry returns the name of the entry the connection came through; see Mux.Entry.
func (*Conn) HTTP2Request ¶
HTTP2Request returns the first request of a cleartext HTTP/2 connection parsed while matching, or nil when none was parsed. It is always set for routes that matched with HTTP2.
func (*Conn) HTTPRequest ¶
HTTPRequest returns the HTTP/1.x request head parsed while matching, or nil when none was parsed. It is always set for routes that matched with HTTP1.
func (*Conn) LocalAddr ¶
LocalAddr returns the PROXY header's destination address when one was parsed, and the connection's local address otherwise.
func (*Conn) NetConn ¶
NetConn returns the connection accepted from the underlying listener. Reading from it directly skips the replayed bytes.
func (*Conn) ProxyHeader ¶
func (c *Conn) ProxyHeader() *proxyproto.Header
ProxyHeader returns the PROXY protocol header, or nil when none was parsed.
func (*Conn) ReadFrom ¶
ReadFrom copies r to the connection, so io.Copy can still use the underlying connection's fast paths.
func (*Conn) RemoteAddr ¶
RemoteAddr returns the PROXY header's source address when one was parsed, and the connection's remote address otherwise.
func (*Conn) RequestedName ¶
RequestedName returns the host name the client asked for, as Input.RequestedName does: the name a matcher set with Input.SetRequestedName, or the SNI of the ClientHello, or the host of the HTTP request without its port, normalized, from what was parsed while matching, or "" without one.
func (*Conn) SetDeadline ¶
SetDeadline sets the read and write deadlines of the underlying connection.
func (*Conn) SetReadDeadline ¶
SetReadDeadline sets the read deadline of the underlying connection. Reads of replayed bytes do not block and ignore it.
func (*Conn) SetWriteDeadline ¶
SetWriteDeadline sets the write deadline of the underlying connection.
func (*Conn) Unread ¶
Unread returns a copy of the bytes that are still to be replayed: the bytes read while matching that Read has not returned yet. Right after Peek or Accept these are all the bytes the client sent first, for example a whole ClientHello for a parser of your own.
type Entry ¶
type Entry struct {
// contains filtered or unexported fields
}
Entry is a named group of the listeners a Mux serves, such as the public HTTPS ports or the ports behind a load balancer. Routes can be limited to entries with RouteConfig.Entries, so that the listeners and the services behind them are configured apart: a service picks the entries it is offered on. Matchers and resolvers see the entry of each connection, whatever the addresses in a PROXY protocol header say, and an entry can have options of its own, such as a shorter sniff timeout or stricter limits.
Entries need no setup: Mux.Entry returns a handle for any name, and the empty name is the entry of Mux.Serve and Mux.ServeConn.
func (*Entry) Config ¶
Config returns the settings that apply to the connections of the entry: those of the Mux with the entry's own on top.
func (*Entry) ResetOptions ¶
func (e *Entry) ResetOptions(opts ...EntryOption)
ResetOptions drops options set for the entry, whose settings then follow the options of the Mux again: the settings of the options given, whatever their values, as in ResetOptions(WithSniffTimeout(0)), or every setting without any.
func (*Entry) SetOptions ¶
func (e *Entry) SetOptions(opts ...EntryOption)
SetOptions sets options for the connections of the entry alone, on top of those of the Mux; options that are not given keep their values, and later changes to the Mux's other options still apply. They take effect as Mux.SetOptions does.
An entry with its own WithRateLimitPerClient keeps buckets of its own, and one with its own WithBanPerClient counts the failures of its clients apart; other entries share those of the Mux. A ban refuses the client on every entry. The per-client pending counts and the connections queued for a route, which the entry's WithMaxPendingPerClient and WithMaxQueued limit, are those of all entries.
type EntryOption ¶
type EntryOption interface {
Option
// contains filtered or unexported methods
}
EntryOption is an Option that can also be set for the connections of one entry alone; see Entry.SetOptions. The options that bound the Mux as a whole, WithMaxPending, WithObserver and WithProxyProtocol, are not entry options.
func WithBanPerClient ¶
func WithBanPerClient(failures int, window, d time.Duration) EntryOption
WithBanPerClient bans clients whose connections keep failing, as scanners' do: once failures connections from Serve of one client matched no route, timed out while sniffing, were refused by a reject route, or sent an invalid PROXY header or none where one is required within window, the client's connections are refused for d, before any byte is read past a PROXY header, and reported with ErrBanned; a banned peer that may send a header is refused before its header. Peers that WithProxyProtocol lets send a header are not banned automatically for their own failures; see WithMaxPendingPerClient. Connections that are closed without sending anything, as health checks are, do not count. Clients are counted as in WithMaxPendingPerClient; Mux.Ban, BanPrefix and Mux.Bans manage bans directly. A non-positive failures or d, the default, disables automatic bans.
func WithDispatchTimeout ¶
func WithDispatchTimeout(d time.Duration) EntryOption
WithDispatchTimeout bounds how long a matched connection waits for its route's Accept. The connection is closed and reported with ErrDispatchTimeout when it expires. A non-positive value waits until the route or the Mux is closed.
func WithMaxPendingPerClient ¶
func WithMaxPendingPerClient(n int) EntryOption
WithMaxPendingPerClient limits how many connections accepted by Serve from one client may be being matched at once, so that a single client cannot use up the WithMaxPending budget with idle connections; as there, a matched connection no longer counts. Connections over the limit are closed at once and reported with ErrPendingLimit. A client is the network, as WithClientPrefix sets it, of the peer of the connection or, for a peer that WithProxyProtocol lets send a header, of the source in its header. For such a peer the per-client rules apply once the header is read, with the peer itself as the client when it sends none where one is optional. The peer's own failures, such as a missing or broken header, and those of its connections without one, do not count toward banning anyone, so that a misconfigured load balancer is not banned with every client behind it; Mux.Ban still bans it. Until the header is read, its connections are bounded by WithMaxPending and the sniff timeout only, so allow headers only from trusted peers. A non-positive value, the default, removes the limit.
func WithMaxQueued ¶
func WithMaxQueued(n int) EntryOption
WithMaxQueued limits how many matched connections may wait for one route's Accept, which, with the dispatch timeout, bounds the connections and memory that a route whose server stalls holds: matched connections no longer count against WithMaxPending. Connections over the limit are closed and reported with ErrQueueFull. RouteConfig.MaxQueued overrides it for a route. A non-positive value removes the limit.
func WithRateLimitPerClient ¶
func WithRateLimitPerClient(perSecond float64, burst int) EntryOption
WithRateLimitPerClient limits how fast one client may open connections that Serve accepts: a token bucket per client refills perSecond tokens a second up to burst, and every connection takes one. Connections without a token are closed at once, before any byte is read past a PROXY header, and reported with ErrRateLimited. Clients are counted as in WithMaxPendingPerClient. WithClientRecords bounds the clients tracked and decides what happens to new ones beyond them. A non-positive rate, the default, disables the limit.
func WithRateLimitPerListener ¶
func WithRateLimitPerListener(perSecond float64, burst int) EntryOption
WithRateLimitPerListener limits how fast each listener served by Serve accepts connections in total, whatever their clients: a token bucket per listener refills perSecond tokens a second up to burst. Connections without a token are closed at once, before any byte is read, and reported with ErrRateLimited. It keeps a flood from many addresses, which per-client limits do not catch, from taking the CPU of every port. A non-positive rate, the default, disables the limit.
type Event ¶
type Event struct {
// Entry is the entry of the listener or of the ServeConn call.
Entry string
// Remote and Local are the connection's addresses, from the PROXY header
// when one was parsed. They are nil for Accept errors.
Remote net.Addr
Local net.Addr
// Route is the route that took the connection, or nil.
Route *Route
// Err is why the connection was closed, or the Accept error; it is nil
// for a delivered connection. A delivered connection whose route handler
// panics is reported once more, after its delivery, with its Route and
// a *PanicError; that event is not counted in Stats again. A close event
// reports a *PanicError and zero Duration if its clock panicked.
Err error
// Elapsed is the time from taking the connection, as in
// WithSniffTimeout, to the decision, measured by the monotonic clock.
Elapsed time.Duration
// Sniffed is the number of bytes read while matching, including a PROXY
// header.
Sniffed int
// Name is the host name the client asked for, as Conn.RequestedName
// returns it, from what matchers parsed, or "".
Name string
// ClientHello, HTTPRequest and HTTP2Request are what matchers parsed of
// the connection, for example to log the fingerprint of a client that
// was refused. Each is set only when its parse succeeded, that is,
// matched a complete head, and is nil otherwise.
ClientHello *tlshello.Hello
HTTPRequest *httphead.Request
HTTP2Request *httphead.Request
// Peer is the address of the TCP peer, which differs from Remote when a
// PROXY header was parsed: the peer is then the proxy that sent it.
Peer net.Addr
// Duration, Read and Written, of an event of WithCloseEvents that
// Closed reports, tell how long after its delivery the connection was
// closed with Conn.Close, and how many bytes it returned to its server
// and took from it. In-flight I/O delays the event until its byte count is known.
Duration time.Duration
Read int64
Written int64
// Closed reports an event of WithCloseEvents: the delivered connection
// was closed.
Closed bool
// Banned reports that this connection's failure banned its client; see
// WithBanPerClient.
Banned bool
// contains filtered or unexported fields
}
Event describes a connection that a Mux delivered or closed, or an Accept error that Serve retries; see WithObserver.
type Filter ¶
Filter restricts what a protocol matcher accepts. HTTP1 takes filters of *httphead.Request and TLS filters of *tlshello.Hello. Filters given to one matcher must all pass; AllOf, AnyOf and NoneOf combine filters of one protocol in any nesting.
type FilterFunc ¶
FilterFunc adapts a function to the Filter interface.
func (FilterFunc[T]) String ¶
func (f FilterFunc[T]) String() string
type FullPolicy ¶
type FullPolicy uint8
FullPolicy is what a table of clients does when it is full; see WithClientRecords.
const ( // FullFailOpen lets clients that no record holds pass unchecked: new // clients are not rate limited, and their failures do not count // toward bans. FullFailOpen FullPolicy = iota // FullFailClosed refuses clients that no record holds: a new client // of a full rate table is refused with ErrRateLimited, and while the // table of bans and failures is full, Serve refuses clients without a // record of failures with ErrBanned. An attacker who fills a table, // with many addresses or failures, then denies service to every new // client until records expire: choose it only where refusing unknown // clients is safer than serving them unchecked. FullFailClosed // FullEvictOldest makes room by forgetting the client seen longest // ago, of a sample of a few records, which then starts over as a new // client. Bans are never evicted: while only bans are left, failures // of new clients are not counted. FullEvictOldest )
type HTTPFilter ¶
HTTPFilter restricts the requests accepted by HTTP1.
func Header ¶
func Header(name string, tokens ...string) HTTPFilter
Header accepts requests with a field of the given name whose value, as a comma-separated list, contains one of the tokens, compared case-insensitively. Without tokens, any value is accepted.
func HeaderRegexp ¶
func HeaderRegexp(name string, re *regexp.Regexp) HTTPFilter
HeaderRegexp accepts requests with a field of the given name whose value matches re. Every field of that name is tried.
func Host ¶
func Host(patterns ...string) HTTPFilter
Host accepts requests whose host, without its port, matches one of the patterns. Patterns work as in SNI; the empty pattern accepts a request without a host. It panics on a pattern that hostmatch.CheckPattern refuses.
func HostRegexp ¶
func HostRegexp(re *regexp.Regexp) HTTPFilter
HostRegexp accepts requests whose host, lowercased and without its port, matches re. Hosts with bytes that no DNS name or IP address has never match.
func Method ¶
func Method(methods ...string) HTTPFilter
Method accepts requests with one of the methods. Methods are case-sensitive.
func Path ¶
func Path(paths ...string) HTTPFilter
Path accepts requests whose decoded path equals one of the paths.
func PathPrefix ¶
func PathPrefix(prefixes ...string) HTTPFilter
PathPrefix accepts requests whose path is one of the prefixes or lies below it: PathPrefix("/api") accepts "/api" and "/api/v1" but not "/apis", and PathPrefix("/api/") accepts only paths below "/api/".
func PathRegexp ¶
func PathRegexp(re *regexp.Regexp) HTTPFilter
PathRegexp accepts requests whose path, decoded and resolved as Path is, matches re.
func Query ¶
func Query(name string, values ...string) HTTPFilter
Query accepts requests whose query string has the parameter with one of the values, or with any value when none are given. Values are compared after decoding and case-sensitively.
func WebSocket ¶
func WebSocket() HTTPFilter
WebSocket accepts WebSocket upgrade requests: the Connection header lists "upgrade" and the Upgrade header lists "websocket".
type HTTPFilterFunc ¶
type HTTPFilterFunc = FilterFunc[*httphead.Request]
HTTPFilterFunc adapts a function to HTTPFilter.
type Input ¶
type Input struct {
// contains filtered or unexported fields
}
Input holds what is known about a connection while it is being matched. Parsed protocol heads are cached and parsing resumes where it stopped, so every matcher on a connection shares one incremental parse.
func NewInput ¶
NewInput returns an Input for running matchers outside a Mux, for example to test a matcher or to match bytes received elsewhere. remote and local are the addresses that address matchers see, and may be nil. Call SetBytes with the bytes received so far before calling a matcher.
Example ¶
Test a custom matcher with bytes and addresses of your choice.
package main
import (
"fmt"
"net"
"net/netip"
"github.com/djylb/portmux"
)
func main() {
office := netip.MustParsePrefix("10.0.0.0/8")
m := portmux.And(portmux.RemoteIP(office), portmux.Prefix("AGENT/1\n"))
in := portmux.NewInput(&net.TCPAddr{IP: net.ParseIP("10.1.2.3"), Port: 5000}, nil)
in.SetBytes([]byte("AGE"), false)
fmt.Println(m.Match(in))
in.SetBytes([]byte("AGENT/1\nhello"), false)
fmt.Println(m.Match(in))
}
Output: NeedMore Match
func (*Input) Bytes ¶
Bytes returns the bytes received so far, after any PROXY protocol header. The slice is only valid during the Match call and must not be modified.
func (*Input) ClientHello ¶
ClientHello parses the input as a TLS ClientHello with tlshello. It returns Match and the parsed hello once a complete, well-formed ClientHello was received, and NoMatch when the input is not one.
func (*Input) Elapsed ¶
Elapsed returns, during a check for silence, how long the connection has been taken without sending anything: the checks run, for connections that sent nothing, at the times that the Silencers among the matchers report. At other calls it returns zero.
func (*Input) Entry ¶
Entry returns the name of the entry the connection came through; see Mux.Entry.
func (*Input) Final ¶
Final reports whether no more bytes will arrive before the decision: the client closed its side, or the sniff size limit was reached. A NeedMore result is treated as NoMatch on final input.
func (*Input) HTTP2Request ¶
HTTP2Request parses the input as a cleartext HTTP/2 connection with prior knowledge, with httphead. It returns Match and the first request once its header block was received, and NoMatch when the input is not such a connection; see HTTP2.
func (*Input) HTTPRequest ¶
HTTPRequest parses the input as the head of an HTTP/1.x request with httphead. It returns Match and the parsed request once the request line and every header field were received, and NoMatch when the input is not an HTTP/1.x request.
func (*Input) LocalAddr ¶
LocalAddr returns the address the client connected to, taken from the PROXY protocol header when one was parsed.
func (*Input) PeerAddr ¶
PeerAddr returns the address of the TCP peer itself. It differs from RemoteAddr when a PROXY protocol header was parsed: the peer is then the proxy that sent it.
func (*Input) ProxyHeader ¶
func (in *Input) ProxyHeader() *proxyproto.Header
ProxyHeader returns the PROXY protocol header, or nil.
func (*Input) RDPCookie ¶
RDPCookie returns the cookie of a Remote Desktop connection request, the routing token that load balancers route by, for example in a resolver: the user name of "Cookie: mstshash=name" or the token of "Cookie: msts=token". It returns NoMatch for input that is not a connection request or has no cookie, and NeedMore while the request is incomplete.
func (*Input) RemoteAddr ¶
RemoteAddr returns the client address, taken from the PROXY protocol header when one was parsed.
func (*Input) RequestedName ¶
RequestedName returns the host name the connection asks for, normalized as hostmatch.Normalize does: the name set with SetRequestedName, or else the SNI of a TLS ClientHello, or the host of an HTTP/1.x or h2c request without its port. The name is empty for a ClientHello or request without one. It returns NoMatch when the connection is none of these or its name is not a valid host name, and NeedMore until it can tell.
func (*Input) SetBytes ¶
SetBytes sets the bytes received so far; final reports that no more will arrive. Each call should pass the bytes of the previous one followed by the new ones, so that parses continue where they stopped; shorter data starts them over. Matchers must not call SetBytes on the Input they are given.
func (*Input) SetEntry ¶
SetEntry sets the entry that Entry reports, for running matchers outside a Mux. Matchers must not call it on the Input they are given.
func (*Input) SetRequestedName ¶
SetRequestedName sets the host name that the connection asks for, for a protocol of your own that names its target: Domain, ResolveHosts, ResolveDomain, Conn.RequestedName and Event.Name then see it, in place of the parsed TLS and HTTP names. It is normalized as hostmatch.Normalize does; a name that is not a valid host name matches no name. Like a value, it lasts for the rest of the matching of the connection.
func (*Input) SetValue ¶
SetValue stores value under key for the rest of the matching of this connection, so that a Matcher of your own can keep the state of an incremental parse across calls, as the parsers of Input do, and share it with other matchers. key must be comparable; to avoid collisions, use a value of an unexported type, as for context keys. SetBytes with shorter data drops the values, as it does the parses.
type ListenerInfo ¶
type ListenerInfo struct {
Entry string
Addr net.Addr
// Stats counts the connections accepted from this listener.
Stats Stats
}
ListenerInfo describes a listener being served.
type Matcher ¶
Matcher decides whether a connection belongs to a route.
Match is first called before any byte arrived, with an empty Input, so that matchers such as RemoteIP can decide at once. It is called again with a longer Input each time it returned NeedMore. A matcher that needs bytes therefore returns NeedMore while the input is too short to decide, including when it is empty. Decisions must be final: once Match or NoMatch has been returned for some input, every longer input that starts with it must get the same answer.
A Matcher is called from many goroutines at once, must not block, and must not retain the Input or its bytes.
func Always ¶
func Always() Matcher
Always matches every connection at once, before reading anything. On an entry whose listeners serve one service alone, a route with Always hands connections over without sniffing, buffering or waiting, so that protocols in which the server speaks first work too.
func AnyBytes ¶
func AnyBytes() Matcher
AnyBytes matches every connection that has sent at least one byte. To take the connections that no other route accepts, prefer a fallback route, which also takes those left undecided at the sniff timeout; see RouteConfig.
func DNS ¶
func DNS() Matcher
DNS matches DNS queries over TCP by their length prefix and header: a standard query with one question and no answers. It matches after the fourteen bytes of the length and the header, and rules other protocols out at their first byte that a query does not have, so that short messages of clients that then wait, such as a PostgreSQL SSL request, are not held back.
func Domain ¶
Domain matches connections whose requested name, as Input.RequestedName returns it, matches one of the patterns: TLS ClientHellos by their SNI and HTTP/1.x and h2c requests by their host, so that one matcher routes a site's HTTPS and HTTP traffic. Patterns work as in hostmatch.Set; it is short for Or(TLS(SNI(patterns...)), HTTP1(Host(patterns...)), HTTP2(Host(patterns...))). It panics on a pattern that hostmatch.CheckPattern refuses.
func HTTP1 ¶
func HTTP1(filters ...HTTPFilter) Matcher
HTTP1 matches connections that start with an HTTP/1.x request and pass every filter. It waits for the complete request head, so the parsed request is always available from Conn.HTTPRequest. Requests with more than one Host header or with obsolete line folding are not matched, since servers disagree on what they mean.
Any method token is accepted, including extension methods. Bytes that cannot start a request line, such as a TLS record, are rejected immediately.
Example ¶
Route by HTTP host and path, including a WebSocket endpoint.
package main
import (
"fmt"
"log"
"net"
"github.com/djylb/portmux"
)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
m := portmux.New()
defer func() { _ = m.Close() }()
_ = m.Listen(portmux.HTTP1(portmux.Host("tunnel.example.com"), portmux.Path("/ws"), portmux.WebSocket()))
api := m.Listen(portmux.HTTP1(portmux.Host("*.example.com"), portmux.PathPrefix("/api/")))
_ = m.Listen(portmux.HTTP1())
go func() { _ = m.Serve(ln) }()
c, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
log.Fatal(err)
}
defer func() { _ = c.Close() }()
_, _ = fmt.Fprint(c, "GET /api/users HTTP/1.1\r\nHost: eu.example.com\r\n\r\n")
conn, err := api.AcceptConn()
if err != nil {
log.Fatal(err)
}
defer func() { _ = conn.Close() }()
req := conn.HTTPRequest()
fmt.Println(req.Method, req.Host, req.Path)
}
Output: GET eu.example.com /api/users
func HTTP2 ¶
func HTTP2(filters ...HTTPFilter) Matcher
HTTP2 matches cleartext HTTP/2 connections with prior knowledge (h2c) whose first request passes every filter, as HTTP1 does for HTTP/1.x: the filters see the request's :method, :path and :authority as Method, Path and Host, and its header fields. It waits for the client connection preface, the SETTINGS frame that follows it and the header block of the first request, so the parsed request is available from Conn.HTTP2Request.
Clients that wait for the server's SETTINGS frame before they send a request, as some gRPC implementations do, cannot be matched by their request; route them with HTTP2Preface, which matches the preface alone.
func HTTP2Preface ¶
func HTTP2Preface() Matcher
HTTP2Preface matches cleartext HTTP/2 connections that start with the client connection preface, as sent with prior knowledge (h2c). HTTP/2 over TLS is matched with TLS(ALPN("h2")).
func LocalIP ¶
LocalIP matches connections to a local address inside one of the prefixes, which tells apart the interfaces of a wildcard listener. The address comes from the PROXY protocol header when one was parsed.
func LocalIPFunc ¶
LocalIPFunc is RemoteIPFunc for the local address, as LocalIP is RemoteIP.
func LocalPort ¶
LocalPort matches connections to one of the local ports, which tells apart the listeners when one Mux serves several. The port comes from the PROXY protocol header when one was parsed.
func MQTT ¶
func MQTT() Matcher
MQTT matches MQTT clients by their CONNECT packet, for protocol versions 3.1, 3.1.1 and 5. It decides once the protocol name and level arrived.
func Named ¶
Named gives m a description, which Snapshot and RouteInfo show instead of its type. Built-in matchers describe themselves, as in TLS(SNI("a.example")).
func Not ¶
Not inverts m: Match becomes NoMatch and NoMatch becomes Match, also when m still needs more of an input that is final.
func OpenVPN ¶
func OpenVPN() Matcher
OpenVPN matches OpenVPN clients over TCP by the hard reset packet that opens a session, of version 2 or 3 (tls-crypt-v2). It decides after three bytes.
func Or ¶
Or matches when any matcher matches. A route already accepts any of its matchers; Or is for nesting inside And and Not.
func ParseMatcher ¶
ParseMatcher parses a matcher from the text that matchers describe themselves with, as in
And(RemoteIP(10.0.0.0/8), TLS(SNI("*.example.com"), MinTLSVersion(1.2)))
FormatMatcher produces text for built-in rules. Strings are Go string literals. Prefixes, ports, durations and versions are written bare. names, which may be nil, supplies custom matchers and filters. A panic in a registered factory is returned as a *PanicError.
Calls nest at most 100 deep, and regular expressions are limited to about 1000 instructions, so that a rule cannot exhaust the stack or make each connection cost much; build larger ones in code.
Example ¶
Read a rule kept as text, with a matcher of the program named in it.
package main
import (
"fmt"
"log"
"net/netip"
"github.com/djylb/portmux"
)
func main() {
names := &portmux.Names{Matchers: map[string]portmux.Matcher{
"office": portmux.RemoteIP(netip.MustParsePrefix("10.0.0.0/8")),
}}
m, err := portmux.ParseMatcher(`And(office, TLS(SNI("admin.example.com"), MinTLSVersion(1.2)))`, names)
if err != nil {
log.Fatal(err)
}
fmt.Println(m)
_, err = portmux.ParseMatcher(`TLS(SNI(admin))`, nil)
fmt.Println(err)
}
Output: And(office, TLS(SNI("admin.example.com"), MinTLSVersion(1.2))) portmux: matcher "TLS(SNI(admin))": expected a string at offset 8
func PostgreSQL ¶
func PostgreSQL() Matcher
PostgreSQL matches PostgreSQL clients by their first message: an SSL or GSSAPI encryption request, a cancel request, or a startup message of protocol version 3. It decides after eight bytes. Clients that ask for encryption send their startup message only after the server's answer.
func RDP ¶
func RDP() Matcher
RDP matches Remote Desktop clients by the X.224 connection request that opens the connection. It decides after six bytes.
func Regexp ¶
Regexp matches connections whose first n bytes match re. It waits for n bytes, or for fewer when the client sends no more or the sniff limit is reached, and then decides once, running re once per connection however often the routes ask again; anchor re with ^ to match from the first byte. Prefix is cheaper for fixed strings.
func RemoteIP ¶
RemoteIP matches connections from a client address inside one of the prefixes. The address comes from the PROXY protocol header when one was parsed. It decides before any byte arrives, so on its own it also routes protocols in which the server speaks first.
Long lists, such as block lists, are looked up by binary search.
func RemoteIPFunc ¶
RemoteIPFunc matches connections from a client whose address contains accepts, as RemoteIP does for a fixed list: for lists that change while the Mux runs, such as a block list behind an atomic.Pointer to an ipmatch.Set, without rebuilding the routes. IPv4-mapped IPv6 addresses are passed as IPv4. contains is called for every connection that the route is tried for, from many goroutines at once, and must not block.
func SOCKS4 ¶
func SOCKS4() Matcher
SOCKS4 matches SOCKS4 and SOCKS4a CONNECT and BIND requests. It decides once the request, including its user ID and SOCKS4a host name, is complete.
func SOCKS5 ¶
func SOCKS5() Matcher
SOCKS5 matches SOCKS5 clients by their greeting: version 5 and a non-empty list of authentication methods. It decides as soon as the greeting is complete, since the client then waits for the server.
func SSH ¶
func SSH() Matcher
SSH matches SSH clients that send their identification string before the server's. Use Silent for clients that wait for the server.
func Silent ¶
Silent matches connections that sent nothing during d after they were accepted, which is how protocols in which the server speaks first look, such as SMTP, FTP, MySQL or SSH clients that wait for the server banner. Shorter durations than one millisecond are raised to it.
The Mux checks silent connections at that time regardless of the order of the routes: the first route that accepts the silent connection gets it, and routes that are still waiting for bytes do not hold it back. A connection that sent anything never matches. Checking for silence extends the read deadline of the connection, which every connection from the net package supports.
func TLS ¶
TLS matches connections that start with a well-formed TLS ClientHello and pass every filter. It waits for the complete ClientHello, so the parsed hello is always available from Conn.ClientHello.
func XMPP ¶
func XMPP() Matcher
XMPP matches XMPP clients and servers by the stream header they open with, an optional XML declaration and a stream:stream element in the jabber:client or jabber:server namespace, or that of a component. It decides once the stream element is complete. It requires both the stream prefix binding and the default content namespace, and rules out headers longer than 2 KiB.
type MatcherFunc ¶
MatcherFunc adapts a function to the Matcher interface. Wrap it in Named to give it a description for Snapshot.
Example ¶
A custom matcher can use the parsed protocol heads.
package main
import (
"fmt"
"slices"
"github.com/djylb/portmux"
)
func main() {
acme := portmux.MatcherFunc(func(in *portmux.Input) portmux.Result {
hello, res := in.ClientHello()
if res != portmux.Match {
return res
}
if slices.Contains(hello.ALPN, "acme-tls/1") {
return portmux.Match
}
return portmux.NoMatch
})
fmt.Println(acme.Match(new(portmux.Input)))
}
Output: NeedMore
func (MatcherFunc) String ¶
func (f MatcherFunc) String() string
String describes f as "MatcherFunc", as FilterFunc does; Named gives it a name of its own.
type Mux ¶
type Mux struct {
// contains filtered or unexported fields
}
Mux distributes connections to routes by their first bytes. It serves any number of listeners, added with Serve and removed by closing them, and connections handed over with ServeConn. Routes can be added, changed and removed at any time. Its methods are safe for concurrent use.
func (*Mux) Add ¶
func (m *Mux) Add(cfg RouteConfig) (*Route, error)
Add adds a route. Each change of the routes rebuilds what connections are matched against, in time that grows with the number of routes, so add many routes at once with Batch. After Close it returns net.ErrClosed with the route, closed.
func (*Mux) Ban ¶
Ban refuses the connections that Serve accepts from client for d, before reading from them, with ErrBanned; the client is banned with its network, of the prefix lengths of WithClientPrefix. A non-positive d lifts the ban. Connections passed to ServeConn are not checked.
func (*Mux) BanPrefix ¶
BanPrefix bans the clients in network for d, as Ban does the network of one client; an IPv4-mapped IPv6 network is banned as IPv4. A non-positive d lifts the ban of network.
func (*Mux) Bans ¶
Bans returns the clients that are banned now, automatically or with Ban or BanPrefix, in no particular order.
func (*Mux) Batch ¶
Batch calls fn with a Batch and applies its changes atomically when fn returns nil. When fn returns an error, nothing is applied and the routes it added are closed. After Close, Batch applies nothing and returns net.ErrClosed.
fn works on a snapshot of the routes and holds no lock, so it may call other methods of the Mux. Its changes are applied on top of the routes as they are when fn returns; when a change no longer applies, for example because another goroutine removed the route meanwhile, Batch applies nothing and returns the error.
Example ¶
Change routes at runtime, for example on a configuration reload.
package main
import (
"fmt"
"log"
"github.com/djylb/portmux"
)
func main() {
m := portmux.New()
defer func() { _ = m.Close() }()
// A fallback route, then named routes for the admin site.
_, _ = m.Add(portmux.RouteConfig{Name: "fallback", Fallback: true})
_, _ = m.Add(portmux.RouteConfig{Name: "admin-http", Matchers: []portmux.Matcher{portmux.HTTP1(portmux.Host("admin.example.com"))}})
_, _ = m.Add(portmux.RouteConfig{Name: "admin-tls", Matchers: []portmux.Matcher{portmux.TLS(portmux.SNI("admin.example.com"))}})
// The admin host changed: update both routes in one step. Their listeners,
// and the servers on them, keep running.
host := "console.example.com"
err := m.Batch(func(b *portmux.Batch) error {
if err := b.SetMatchers(b.Route("admin-http"), portmux.HTTP1(portmux.Host(host))); err != nil {
return err
}
return b.SetMatchers(b.Route("admin-tls"), portmux.TLS(portmux.SNI(host)))
})
if err != nil {
log.Fatal(err)
}
// The admin site was turned off.
_ = m.Route("admin-tls").Close()
for _, r := range m.Routes() {
fmt.Println(r.Name(), r.Priority())
}
}
Output: admin-http 0 fallback 0
func (*Mux) Close ¶
Close closes the listeners and every connection that was not delivered yet. Routes then return net.ErrClosed from Accept. Delivered connections are not affected. The caller that closes the listeners receives their first error. An overlapping or reentrant call returns net.ErrClosed while resources are being closed. Calls after closure completes return nil.
func (*Mux) Config ¶
Config returns the settings of the Mux, as its options set them; see Entry.Config for those of an entry with options of its own.
func (*Mux) Entries ¶
Entries returns, sorted, the names of the entries that routes are limited to, that have options of their own or whose listeners the Mux serves. A name passed to Mux.Entry that is none of them, such as a misspelt one, has nothing of its own: its connections take the routes and options of every entry, which a program can check for when it configures the entries.
func (*Mux) LastObserverPanic ¶
func (m *Mux) LastObserverPanic() *PanicError
LastObserverPanic reports the most recent observer panic, or nil. The returned error is read-only.
func (*Mux) Listen ¶
Listen adds an unnamed route with priority 0 for the matchers and returns it, a net.Listener of the connections it matches. Routes with equal priority are tried in the order they were added, so for a static setup Listen routes can simply be added from specific to general. After Close it returns a closed route, whose Accept returns net.ErrClosed, as a listener does. Listen panics on a nil matcher and without matchers, as a route without them matches nothing: take every connection with AnyBytes or Always, and add a route without matchers, such as a target of resolvers, with Add.
func (*Mux) Serve ¶
Serve accepts connections from ln until ln fails or the Mux is shut down, and closes ln when it returns. Serve may run for several listeners at once; closing one of them only stops its Serve call. Temporary Accept errors are retried with a growing delay.
After Shutdown or Close, Serve returns net.ErrClosed. Its connections belong to the entry with the empty name; Entry serves listeners of other entries.
Example (Nested) ¶
Terminate TLS on one route and match the protocol inside it with a second Mux.
package main
import (
"crypto/tls"
"io"
"log"
"net"
"net/http"
"github.com/djylb/portmux"
)
func serveAgents(l net.Listener) {
for {
c, err := l.Accept()
if err != nil {
return
}
go func() {
defer func() { _ = c.Close() }()
_, _ = io.Copy(c, c)
}()
}
}
func publicHandler() http.Handler { return http.NotFoundHandler() }
func main() {
outer := portmux.New()
secure := outer.Listen(portmux.TLS(portmux.SNI("tunnel.example.com")))
inner := portmux.New()
agents := inner.Listen(portmux.Prefix("AGENT/1\n"))
web := inner.Listen(portmux.HTTP1())
go func() { _ = inner.Serve(tls.NewListener(secure, &tls.Config{ /* certificates */ })) }()
go serveAgents(agents)
go func() { _ = http.Serve(web, publicHandler()) }()
ln, err := net.Listen("tcp", ":443")
if err != nil {
log.Fatal(err)
}
log.Fatal(outer.Serve(ln))
}
Output:
func (*Mux) ServeConn ¶
ServeConn matches c and hands it to a route, in the calling goroutine. It returns nil once a route accepted c; for a route with a handler, it calls the handler and returns when the handler returns, or a *PanicError when the handler panicked. Otherwise it closes c and returns the reason, which the observer of WithObserver also receives.
Connections passed to ServeConn skip the admission that Serve applies: the pending limits, the per-client rate limits and bans, and the listener rate. To keep them for connections that a program obtains itself, hand them to Serve through a net.Listener of its own, such as a channel listener. The sniff timeout and silence checks rely on c supporting read deadlines. c belongs to the entry with the empty name; Entry routes connections of other entries.
func (*Mux) SetOptions ¶
SetOptions changes options while the Mux serves; options that are not given keep their values. The options apply to the connections accepted from then on: a connection keeps the settings in effect when it was accepted, its timeouts, sizes and limits, its observer and whether its close is reported, so a new observer does not see the events of connections already taken, including their close events. WithMaxPending, which bounds the Mux as a whole, applies at once, but lowering it closes nothing at once: for each connection it accepts over the limit, Serve evicts the oldest undecided one, as at the limit, and waits until enough pending connections are gone. A new WithRateLimitPerClient starts every client with a full bucket.
func (*Mux) Shutdown ¶
Shutdown stops taking new connections, closes the listeners, and waits until every pending connection was delivered or rejected, or until ctx is done. It then closes the Mux. It returns ctx's error if ctx ended the wait, and otherwise the first error from closing a listener. Routes keep accepting connections while Shutdown waits, so their servers must still be running. Shutdown does not wait for handlers to return.
Example ¶
Stop taking connections but deliver those already being matched.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/djylb/portmux"
)
func main() {
m := portmux.New()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := m.Shutdown(ctx); err != nil {
log.Print(err)
}
fmt.Println(m.Stats().Pending)
}
Output: 0
func (*Mux) Snapshot ¶
Snapshot returns the current listeners, routes and counters, for example for a status page. The routes are taken at one moment, so their order and configuration are consistent with each other.
func (*Mux) Unban ¶
Unban lifts the bans of the networks that hold client, of the prefix lengths of WithClientPrefix now or when they were set, and reports whether it was banned.
func (*Mux) UnbanPrefix ¶
UnbanPrefix lifts the ban of network, as BanPrefix or Ban set it, and reports whether it was banned. Bans of other networks that hold some of its addresses stay; Unban lifts every ban of an address.
type Names ¶
type Names struct {
// Matchers, HTTPFilters and TLSFilters are found by an identifier without
// arguments, such as office in And(office, TLS()). They keep the name as
// their description, so that the parsed matcher prints the text again.
Matchers map[string]Matcher
HTTPFilters map[string]HTTPFilter
TLSFilters map[string]TLSFilter
// MatcherFuncs, HTTPFilterFuncs and TLSFilterFuncs build matchers and
// filters from calls with arguments, such as Country("CN") or
// JA4("t13d1516h2_8daaf6152771_e5627efa2ab1"): they are called with the
// arguments as text, strings unquoted and bare words as written. Their
// results should describe themselves as the call, so that the parsed
// matcher prints the text again. A built-in name cannot be replaced.
MatcherFuncs map[string]func(args ...string) (Matcher, error)
HTTPFilterFuncs map[string]func(args ...string) (HTTPFilter, error)
TLSFilterFuncs map[string]func(args ...string) (TLSFilter, error)
}
Names supplies the matchers and filters of your own that ParseMatcher finds by name. Each is used where its kind is expected.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures a Mux; see New and Mux.SetOptions.
func WithClientPrefix ¶
WithClientPrefix sets the networks that the per-client rules, WithMaxPendingPerClient, WithRateLimitPerClient and WithBanPerClient, and Mux.Ban count a client as: the IPv4 /v4 and the IPv6 /v6 network of its address. The defaults, 32 and 64, take an IPv4 address and the /64 network that one IPv6 client usually holds; a shorter IPv6 prefix such as 56 groups clients whose provider hands out larger networks. Values out of range, below 1 or above 32 and 128, select the defaults. A change applies to new connections and bans; bans already set keep the networks they were set for, and still refuse their clients, while failures toward bans and the tokens of WithRateLimitPerClient start over for the new networks.
func WithClientRecords ¶
func WithClientRecords(n int, full FullPolicy) Option
WithClientRecords bounds to n the clients that the Mux keeps records of in each of its tables: the token buckets of WithRateLimitPerClient, of the Mux and of each entry with its own, and the failures and bans of WithBanPerClient. Records are forgotten once they no longer matter, when a bucket is full again or a failure window has passed; under a flood of new clients, n bounds the memory they take, and full decides what happens to clients the table has no room for. Zero selects DefaultMaxClientRecords and a negative n removes the limit. Bans set with Mux.Ban and BanPrefix are kept whatever the limit. Tables grow with the clients they hold, not with n.
func WithClock ¶
WithClock makes the Mux take the time of its bans, rate limits and close events from c instead of the system clock, so that tests can drive them with a timeshim.Fake. Only New takes it: SetOptions panics on it. Sniff and dispatch timeouts follow the system clock, as they are deadlines of the connections.
func WithCloseEvents ¶
WithCloseEvents makes the observer of WithObserver receive one more Event for each delivered connection, when its server closes it with Conn.Close: with Closed set, how long it was open and how many bytes it carried, for access logs. The Mux then counts the bytes of delivered connections, which uses a tracking record per connection and takes a lock at the start and end of each I/O operation. Outstanding I/O delays publication of the close event. If the clock panics, the event carries a *PanicError and zero Duration. Each connection uses the observer in effect when it was accepted.
func WithMaxPending ¶
WithMaxPending limits how many connections accepted by Serve may be being matched at once. At the limit, Serve closes the undecided connection that was accepted first, reported with ErrEvicted, to make room for the next one; legitimate clients are decided within a round trip, so the oldest undecided connections are the idle and slow ones. Serve waits for the evicted connection to give its slot back, which leaves further clients in the kernel's accept queue meanwhile. A matched connection gives its slot back at once: those waiting for their route to accept them are bounded by WithMaxQueued and the dispatch timeout, so that a route that the same Mux serves, as when matching again inside TLS, never waits for slots that connections waiting for it hold. A connection matched again because its route was removed while it waited takes no slot again; the sniff timeout bounds it. A non-positive value removes the limit.
func WithObserver ¶
WithObserver sets a function called with an Event for every connection that the Mux delivers or closes, from Serve or ServeConn, and for the temporary Accept errors that Serve retries, for access logs, metrics and error reports. Connections closed because the Mux was closed are not reported. The function must be safe for concurrent use. It runs synchronously, for limit errors in the accept loop, so it must be cheap under attack: prefer counting to logging every rejected connection. It may call the methods of the Mux, but not wait for Shutdown, which waits for the Serve call that may be calling it: start Shutdown in a goroutine. A connection reports to the observer that was set when it was accepted, including the event of WithCloseEvents when it is closed, so setting another observer, or none, does not affect the connections already taken.
type PanicError ¶
type PanicError = panicerr.PanicError
PanicError records a panic recovered while running a callback. Value holds the original panic and Stack identifies the goroutine that recovered it.
func NewPanicError ¶
func NewPanicError(value any) *PanicError
NewPanicError captures the stack of the goroutine that recovered value.
type ParseError ¶
type ParseError struct {
Text string
Offset int // byte offset of the problem in Text
Msg string
// Err is the error of a function of Names that failed, or nil.
Err error
}
ParseError reports text that ParseMatcher cannot parse.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
func (*ParseError) Unwrap ¶
func (e *ParseError) Unwrap() error
Unwrap returns the error of a function of Names, or nil.
type PeekOption ¶
type PeekOption interface {
Option
// contains filtered or unexported methods
}
PeekOption is an Option that Peek takes as well: WithSniffTimeout, WithMaxSniffBytes and WithProxyProtocol.
func WithProxyProtocol ¶
func WithProxyProtocol(policy func(entry string, peer, local net.Addr) proxyproto.Policy) PeekOption
WithProxyProtocol enables PROXY protocol v1 and v2 headers, parsed with github.com/djylb/netx/proxyproto. The policy is called for each connection with its entry, its peer and its local address, and decides whether a header is Required, Optional or to be ignored: per entry for the ports behind a load balancer, or per peer for the balancer's addresses. A parsed header is removed from the stream before matching, and its addresses replace those of the delivered Conn. Peek calls the policy with the empty entry. A missing required header is reported with proxyproto.ErrNoHeader, an invalid one with an error wrapping proxyproto.ErrMalformed. An optional header is taken to be missing when the client sends nothing until a Silent check or the sniff timeout, so that Silent routes, and routes that decide without bytes such as those with Always, still take clients that wait for the server; the latter only at the sniff timeout, so give their entries a policy of Required or Ignore.
Use this option rather than a proxyproto.Listener in front of the Mux: the header is then read within the sniff timeout and the pending limits, and the accept loop never waits for it. The policy, too, runs in the connection's goroutine once it has a pending slot, so a slow policy holds up only its connection and a panicking one closes only its connection. With a policy set, Serve applies the per-client rules there too, to the source of the header for a peer that sends one, and checks only bans of the peer when accepting; see WithMaxPendingPerClient.
Only trusted peers such as a load balancer should be allowed to send a header, since it lets the peer choose the reported client address; TrustPeers gives a policy for a list of their addresses.
Example ¶
Accept PROXY protocol headers from a trusted load balancer only, and serve the admin site to the office network only.
package main
import (
"log"
"net"
"net/netip"
"github.com/djylb/netx/proxyproto"
"github.com/djylb/portmux"
)
func main() {
lb := netip.MustParsePrefix("10.0.0.0/24")
office := netip.MustParsePrefix("203.0.113.0/24")
m := portmux.New(portmux.WithProxyProtocol(func(_ string, peer, _ net.Addr) proxyproto.Policy {
if tcp, ok := peer.(*net.TCPAddr); ok && lb.Contains(tcp.AddrPort().Addr().Unmap()) {
return proxyproto.Required
}
return proxyproto.Ignore
}))
// RemoteIP sees the client address from the PROXY header.
_ = m.Listen(portmux.And(portmux.RemoteIP(office), portmux.TLS(portmux.SNI("admin.example.com"))))
_ = m.Listen(portmux.TLS())
ln, err := net.Listen("tcp", ":443")
if err != nil {
log.Fatal(err)
}
log.Fatal(m.Serve(ln))
}
Output:
type Peeker ¶
type Peeker struct {
// contains filtered or unexported fields
}
Peeker is PeekAny with its matchers and options prepared once, for a server that peeks at every connection it takes the same way. A Peeker is safe for concurrent use.
func NewPeeker ¶
func NewPeeker(matchers []Matcher, opts ...PeekOption) *Peeker
NewPeeker prepares matchers and opts for Peeker.Peek. It panics without matchers or on a nil one. A panic in Silences is reported by each Peek.
type ResolveFunc ¶
ResolveFunc chooses the route of a connection in your own code, typically by looking up the ClientHello's SNI or the request's Host in a table of your own, which costs the same for any number of targets. It is called like a matcher, first before any byte arrives and then after every read, and returns:
- a route of the same Mux and Match: the connection goes to that route. It may be a route without matchers, which serves only as a target for resolvers, a reject route, which closes the connection, or nil for the resolver route's own listener;
- NeedMore while it cannot decide yet, which holds the later routes back;
- NoMatch to leave the connection to the later routes.
Its decisions must be final, as a matcher's are. It runs in the Mux's goroutines, must not block, and must not retain the Input. A connection it sends to a closed route is closed and reported with ErrRouteClosed, and one it sends to a route limited to other entries with ErrEntryMismatch.
func ResolveDomain ¶
func ResolveDomain(hosts *hostmatch.Map[*Route]) ResolveFunc
ResolveDomain returns a resolver that routes connections by the name they ask for to the route of the most specific pattern of hosts; see ResolveHosts. A pattern whose route is nil sends the connection to the resolver route itself.
func ResolveHosts ¶
func ResolveHosts[V any](hosts *hostmatch.Map[V], pick func(in *Input, pattern string, v V) (*Route, bool)) ResolveFunc
ResolveHosts returns a resolver that routes connections by the name they ask for, as Input.RequestedName returns it, through hosts: pick is called with the patterns that match the name, most specific first, and their values, and the first route it accepts takes the connection. A nil route sends the connection to the resolver route itself. A route that is closed is passed over as pick not accepting it, so that replacing a route, by adding the new one, pointing hosts to it and closing the old one, sends no connection to the closed one. When pick accepts no pattern, the connection is left to the next routes.
pick sees the Input too, so that a value can hold several targets, for example one for TLS and one for HTTP. Like a resolver, it must not block. Changes to hosts apply to the next decisions.
Example ¶
Keep an HTTPS and an HTTP target per name, and fall back to a wider pattern when a name has no target for the protocol.
package main
import (
"fmt"
"log"
"github.com/djylb/portmux"
"github.com/djylb/portmux/hostmatch"
)
func main() {
m := portmux.New()
defer func() { _ = m.Close() }()
target := func(name string) *portmux.Route {
r, err := m.Add(portmux.RouteConfig{Name: name})
if err != nil {
log.Fatal(err)
}
return r
}
type site struct{ https, http *portmux.Route }
var sites hostmatch.Map[site]
sites.Set("*.example.com", site{https: target("passthrough"), http: target("web")})
sites.Set("shop.example.com", site{https: target("shop")}) // HTTPS only
resolve := portmux.ResolveHosts(&sites, func(in *portmux.Input, _ string, s site) (*portmux.Route, bool) {
if _, res := in.ClientHello(); res == portmux.Match {
return s.https, s.https != nil
}
return s.http, s.http != nil
})
if _, err := m.Add(portmux.RouteConfig{Name: "sites", Resolve: resolve}); err != nil {
log.Fatal(err)
}
in := portmux.NewInput(nil, nil)
in.SetBytes([]byte("GET / HTTP/1.1\r\nHost: shop.example.com\r\n\r\n"), false)
r, res := resolve(in)
fmt.Println(r.Name(), res)
}
Output: web Match
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route is a net.Listener for the connections matched by one route of a Mux. Its configuration can be changed while the Mux serves; the change applies to the next matching decision of every undelivered connection.
func (*Route) Accept ¶
Accept waits for the next connection matched by the route. The connection is a *Conn. Routes that reject or have a handler deliver nothing to Accept, which then returns only when the route is closed.
func (*Route) AcceptConn ¶
AcceptConn is Accept with the concrete connection type.
func (*Route) Addr ¶
Addr returns the address of the listener that serves the route's entries. When several listeners serve them, it returns an address that lists them.
func (*Route) Close ¶
Close removes the route from its Mux and closes the listener: Accept returns net.ErrClosed and the route stops matching. Connections that were matched to it but not accepted yet are matched again against the remaining routes. Closing a removed route does nothing.
func (*Route) Entries ¶
Entries returns the entries the route is limited to, or nil when it applies to every entry.
func (*Route) Fallback ¶
Fallback reports whether the route takes connections that no route matched.
func (*Route) Matched ¶
Matched returns how many connections the route has matched. For a reject route these are the connections it closed.
func (*Route) SetDispatchTimeout ¶
SetDispatchTimeout changes the route's dispatch timeout; see RouteConfig.DispatchTimeout. It applies to connections matched from then on, and returns net.ErrClosed for a removed route.
func (*Route) SetEntries ¶
SetEntries limits the route to connections of the entries, or lets it apply to every entry when none are given. It returns net.ErrClosed for a removed route.
func (*Route) SetHandler ¶
SetHandler changes the route's handler; see Batch.SetHandler. It returns net.ErrClosed for a removed route.
func (*Route) SetMatchers ¶
SetMatchers replaces the route's matchers. Without matchers the route is paused: it matches nothing but its listener stays open. It returns net.ErrClosed for a removed route.
func (*Route) SetMaxConns ¶
SetMaxConns changes the limit of open connections; see RouteConfig.MaxConns. It returns net.ErrClosed for a removed route.
func (*Route) SetMaxQueued ¶
SetMaxQueued changes the route's limit of queued connections; see RouteConfig.MaxQueued. Connections already queued stay queued. It returns net.ErrClosed for a removed route.
func (*Route) SetPriority ¶
SetPriority changes the route's priority. It returns net.ErrClosed for a removed route.
func (*Route) SetResolve ¶
func (r *Route) SetResolve(resolve ResolveFunc) error
SetResolve changes the route's resolver; see Batch.SetResolve. It returns net.ErrClosed for a removed route.
type RouteConfig ¶
type RouteConfig struct {
// Resolve lets your code choose the route, from everything known about
// the connection; see ResolveFunc. A resolver route is one rule among
// the others: it is tried in priority order, and its Matchers, if any,
// are conditions that must match before the resolver is asked, as in
// "TLS from the office, then look the name up".
Resolve ResolveFunc
// Name identifies the route for Mux.Route and Batch.Route. It is
// optional. A non-empty name must be unique within the Mux.
Name string
// Entries limits the route to connections of these entries; see Entry.
// Without entries the route applies to every entry, which suits rules
// such as block lists; a global route that waits for bytes also holds
// back the later routes of every entry, so give such routes entries or a
// lower priority than the routes of dedicated entries. Entries also bind
// resolvers: a resolver that sends a connection to a route limited to
// other entries gets it closed with ErrEntryMismatch.
Entries []string
// Matchers select the connections of the route; one of them matching is
// enough. A route without matchers matches nothing, which pauses it while
// its listener stays open.
Matchers []Matcher
// Priority orders the routes. Higher priorities are tried first, and
// routes with equal priority in the order they were added.
Priority int
// Reject makes the route close the connections it matches, reported with
// ErrRefused, instead of delivering them; its Accept never returns a
// connection. With a high priority and address matchers it is a block
// list that closes connections before reading from them. Matchers rule
// out what they cannot parse or find ambiguous, such as a request with two
// Host fields, so a reject route does not see it: where reject routes
// guard the others, make the fallback a reject route too, with Fallback
// and Reject, which closes whatever no other route took.
Reject bool
// Fallback makes the route take the connections that no other route
// matched, after all of them, whatever their priorities: those every
// route ruled out, and those that sent bytes but stayed undecided until
// the sniff timeout. Clients that sent nothing are not taken; route them
// with Silent. A fallback route has no matchers. Of several fallback
// routes, the one with the highest priority is used and the others stand
// by, so a replacement can be added before the old one is removed.
Fallback bool
// MaxConns limits the connections the route has open: delivered, or
// waiting for Accept, and not closed yet. Connections over the limit are
// closed and reported with ErrConnLimit. Zero means no limit; a negative
// value is not valid.
MaxConns int
// DispatchTimeout and MaxQueued override WithDispatchTimeout and
// WithMaxQueued for the route, so that a route whose server is
// slow to accept can wait longer, or queue less, than the others of its
// entry. Zero keeps the entry's setting, and a negative value removes the
// limit. They do not apply to a route with a Handler.
DispatchTimeout time.Duration
MaxQueued int
// Handler, when set, serves the route's connections instead of Accept:
// each matched connection is passed to it in the goroutine that matched
// it, once it no longer counts as pending. This saves the accept loop,
// the hand-over to it and the queue, so dispatch timeouts and
// WithMaxQueued do not apply. The handler owns the connection and must
// close it. A panic in the handler closes the connection and is
// reported to the observer as a *PanicError, as one in a matcher is.
// Accept of such a route never returns a connection.
Handler func(c *Conn)
}
RouteConfig describes a route for Mux.Add and Batch.Add.
Example (Handler) ¶
Serve a route with a handler instead of an accept loop, and a dedicated entry whose connections go to it unread.
package main
import (
"io"
"log"
"net"
"github.com/djylb/portmux"
)
func main() {
m := portmux.New()
_, err := m.Add(portmux.RouteConfig{
Entries: []string{"echo"},
Matchers: []portmux.Matcher{portmux.Always()},
Handler: func(c *portmux.Conn) {
defer func() { _ = c.Close() }()
_, _ = io.Copy(c, c)
},
})
if err != nil {
log.Fatal(err)
}
ln, err := net.Listen("tcp", ":7")
if err != nil {
log.Fatal(err)
}
log.Fatal(m.Entry("echo").Serve(ln))
}
Output:
type RouteInfo ¶
type RouteInfo struct {
Name string
Priority int
// Entries lists the entries the route is limited to, or is nil.
Entries []string
// Matchers describes the matchers, as in TLS(SNI("a.example")).
Matchers []string
Reject bool
Fallback bool
// Resolver reports a route that chooses routes with a ResolveFunc.
Resolver bool
// Handler reports a route whose connections go to a handler.
Handler bool
// Active reports whether the route is tried now: it was not removed and
// has matchers or a resolver, or it is the fallback route in use. Routes
// without matchers are not tried but still take what resolvers send them.
Active bool
// Removed reports whether the route was closed or removed.
Removed bool
// Matched counts the connections the route has matched.
Matched uint64
// Queued is the number of matched connections waiting for Accept.
Queued int64
// Open is the number of connections the route has open: delivered, or
// waiting for Accept, and not closed yet.
Open int64
// MaxConns is the limit of Open, or zero.
MaxConns int
// DispatchTimeout and MaxQueued are the route's own settings, or zero;
// see RouteConfig.
DispatchTimeout time.Duration
MaxQueued int
// Accepting is the number of Accept calls waiting for a connection. A
// route without a handler whose Accepting stays zero has no server taking
// its connections.
Accepting int64
}
RouteInfo describes the state of a route at one moment.
type Silencer ¶
Silencer is implemented by matchers that decide on silence, as Silent does. Silences reports, by calling add, the times after taking a connection at which the Mux checks a connection that has sent nothing again; the matcher reads Input.Elapsed then. And, Or, Not and Named report the durations of the matchers they hold. A matcher of your own that waits for silence must implement Silencer, as one that calls Silent inside a MatcherFunc is never checked again; or it can be combined with Silent by And.
type Snapshot ¶
type Snapshot struct {
// Listeners lists the listeners being served and their entries.
Listeners []ListenerInfo
// Routes describes the routes in matching order, fallback routes last.
Routes []RouteInfo
Stats Stats
}
Snapshot is the state of a Mux at one moment.
type SniffOption ¶
type SniffOption interface {
EntryOption
PeekOption
}
SniffOption is an option of the sniffing that an entry and Peek can set too: WithSniffTimeout and WithMaxSniffBytes.
func WithMaxSniffBytes ¶
func WithMaxSniffBytes(n int) SniffOption
WithMaxSniffBytes limits how many bytes are buffered while matching, not counting a PROXY protocol header. Once the limit is reached, matchers that still need more bytes are treated as not matching. A non-positive value selects DefaultMaxSniffBytes, and values above MaxSniffBytesLimit are lowered to it.
func WithSniffTimeout ¶
func WithSniffTimeout(d time.Duration) SniffOption
WithSniffTimeout bounds the time from taking a connection until it is matched, including reading a PROXY protocol header. Serve takes a connection once it has a pending slot, so the wait for one, see WithMaxPending, does not count. A connection that is still undecided when it expires is closed and reported with ErrSniffTimeout. A non-positive value disables the limit.
type Stats ¶
type Stats struct {
// Accepted counts the connections accepted by Serve or passed to
// ServeConn.
Accepted uint64
// Delivered counts the connections that a route accepted or passed to
// its handler.
Delivered uint64
// Rejected counts the connections closed without being delivered. The
// fields after Pending break it down by reason.
Rejected uint64
// Pending is the number of connections being matched or waiting for
// their route to accept them. Only those being matched count against
// WithMaxPending, so Pending can be above that limit.
Pending int64
// Open is the number of connections delivered, or waiting for Accept,
// and not closed yet with Conn.Close.
Open int64
// NoMatch counts connections that no route matched.
NoMatch uint64
// Refused counts connections closed by reject routes.
Refused uint64
// Timeouts counts sniff and dispatch timeouts.
Timeouts uint64
// Evicted counts undecided connections closed at the pending limit.
Evicted uint64
// Limited counts connections closed by the rate and pending limits, or
// because their route had too many connections queued or open
// (ErrQueueFull, ErrConnLimit).
Limited uint64
// Banned counts connections closed because their client is banned.
Banned uint64
// Failed counts the rest: clients that closed or reset the connection,
// invalid PROXY headers, panics of matchers, resolvers and PROXY policies,
// and connections closed by Close. A connection whose handler panics was
// counted as delivered.
Failed uint64
}
Stats is a snapshot of connection counters, of a Mux or of one listener.
type TLSFilter ¶
TLSFilter restricts the ClientHellos accepted by TLS.
func MinTLSVersion ¶
MinTLSVersion accepts ClientHellos that offer at least version v, such as tls.VersionTLS12, judged as servers negotiate: by the highest version of supported_versions up to TLS 1.3 or, without that extension, by legacy_version up to TLS 1.2. It turns away clients that only speak older versions.
func SNI ¶
SNI accepts ClientHellos whose server name matches one of the patterns, as hostmatch.Set matches them: a host name, "*.example.com" for any name below example.com, ".example.com" for example.com and the names below it, or "*" for any name. The empty pattern accepts a ClientHello without SNI. Names compare case-insensitively. It panics on a pattern that hostmatch.CheckPattern refuses.
type TLSFilterFunc ¶
type TLSFilterFunc = FilterFunc[*tlshello.Hello]
TLSFilterFunc adapts a function to TLSFilter.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fingerprint computes the JA4 and JA3 fingerprints of TLS ClientHellos parsed by tlshello, which identify the TLS library of a client, and filters routes by them.
|
Package fingerprint computes the JA4 and JA3 fingerprints of TLS ClientHellos parsed by tlshello, which identify the TLS library of a client, and filters routes by them. |
|
fpnames
Package fpnames lets portmux.ParseMatcher read the filters of package fingerprint.
|
Package fpnames lets portmux.ParseMatcher read the filters of package fingerprint. |
|
Package hostmatch matches host names against patterns such as "*.example.com" and ".example.com".
|
Package hostmatch matches host names against patterns such as "*.example.com" and ".example.com". |
|
Package httphead parses the head of the first HTTP request of a connection, as a sniffer sees it: Parse reads an HTTP/1.x request line and header fields, and ParseHTTP2 the first request of a cleartext HTTP/2 connection with prior knowledge (h2c), whose header block it decodes with HPACK.
|
Package httphead parses the head of the first HTTP request of a connection, as a sniffer sees it: Parse reads an HTTP/1.x request line and header fields, and ParseHTTP2 the first request of a cleartext HTTP/2 connection with prior knowledge (h2c), whose header block it decodes with HPACK. |
|
Package httproute routes HTTP requests by host, path, method and header fields to actions: a reverse proxy to a backend reached through the caller's dial function, a redirect, or a fixed response.
|
Package httproute routes HTTP requests by host, path, method and header fields to actions: a reverse proxy to a backend reached through the caller's dial function, a redirect, or a fixed response. |
|
internal
|
|
|
leakcheck
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them.
|
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them. |
|
panicerr
Package panicerr captures panics at package callback boundaries.
|
Package panicerr captures panics at package callback boundaries. |
|
pmap
Package pmap is a persistent map from strings to values: a hash array mapped trie whose updates copy only the path to the changed entry, so that versions share every part they have in common.
|
Package pmap is a persistent map from strings to values: a hash array mapped trie whose updates copy only the path to the changed entry, so that versions share every part they have in common. |
|
testutil
Package testutil builds and captures the protocol bytes that the tests of portmux and its packages feed to parsers.
|
Package testutil builds and captures the protocol bytes that the tests of portmux and its packages feed to parsers. |
|
Package ipmatch looks IP addresses up in sets of prefixes, such as block lists and office networks.
|
Package ipmatch looks IP addresses up in sets of prefixes, such as block lists and office networks. |
|
Package tlshello parses the TLS ClientHello that opens a TLS connection, as a sniffer sees it before any handshake: Parse reads it at once and Scanner as its bytes arrive, also when it spans several records.
|
Package tlshello parses the TLS ClientHello that opens a TLS connection, as a sniffer sees it before any handshake: Parse reads it at once and Scanner as its bytes arrive, also when it spans several records. |