portmux

package module
v0.0.0-...-c7256ab Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 31 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

portmux

Serve multiple protocols on one port by sniffing the first bytes of each connection — HTTP/1, h2c, TLS (SNI/ALPN/JA4), PROXY protocol, SSH, SOCKS, databases and custom prefixes — and routing them to separate net.Listeners or handlers. Routes, limits and options change while serving.

Requires Go 1.26. Besides the standard library it uses only netx for PROXY protocol headers and timeshim as its injectable clock.

Install

go get github.com/djylb/portmux

Packages

Package Contents
portmux Mux, routes, entries, matchers, filters, delivered connections, text rules
portmux/hostmatch Set and Map of host name patterns such as *.example.com
portmux/ipmatch Set of IP prefixes, for block lists and networks
portmux/tlshello TLS ClientHello parser
portmux/httphead HTTP/1.x and h2c request head parsers, with HPACK
portmux/fingerprint JA4 and JA3 fingerprints of ClientHellos, and filters by them
portmux/httproute HTTP request routing: reverse proxy, redirects, header rules, error pages

A program carries only the packages it imports: the tool packages work without a Mux, only fingerprint imports hash functions, and only httproute imports net/http and crypto/tls.

Usage

package main

import (
	"crypto/tls"
	"io"
	"log"
	"net"
	"net/http"
	"time"

	"github.com/djylb/portmux"
)

func main() {
	m := portmux.New()

	// Routes with equal priority are tried in the order they were added.
	agents := m.Listen(portmux.Prefix("AGENT/1\n"))
	admin := m.Listen(portmux.TLS(portmux.SNI("admin.example.com")))
	site := m.Listen(portmux.TLS())
	web := m.Listen(portmux.HTTP1())
	ssh := m.Listen(portmux.SSH(), portmux.Silent(2*time.Second))

	cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
	if err != nil {
		log.Fatal(err)
	}
	config := &tls.Config{Certificates: []tls.Certificate{cert}}

	go forward(agents, "127.0.0.1:9000")
	go forward(ssh, "127.0.0.1:22")
	go http.Serve(tls.NewListener(admin, config), http.FileServer(http.Dir("admin")))
	go http.Serve(tls.NewListener(site, config), http.FileServer(http.Dir("www")))
	go http.Serve(web, http.RedirectHandler("https://example.com/", http.StatusMovedPermanently))

	ln, err := net.Listen("tcp", ":443")
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(m.Serve(ln))
}

// forward proxies every connection of l to addr.
func forward(l net.Listener, addr string) {
	for {
		c, err := l.Accept()
		if err != nil {
			return
		}
		go func() {
			defer c.Close()
			backend, err := net.Dial("tcp", addr)
			if err != nil {
				return
			}
			defer backend.Close()
			go io.Copy(backend, c)
			io.Copy(c, backend)
		}()
	}
}
  • Every route is a net.Listener. Its Accept returns a *portmux.Conn that replays the sniffed bytes first, so servers see the stream from its first byte.
  • Routes are tried by priority and then in the order they were added; while a route still needs bytes, the routes after it wait. A connection that no route takes is closed.
  • Routing happens once per connection: a keep-alive HTTP connection stays on the route of its first request.

Matchers

Matcher Matches
Prefix(p...), Regexp(re, n) The first bytes
HTTP1(filters...), HTTP2(filters...) HTTP/1.x requests, and h2c by its first request
TLS(filters...) TLS ClientHellos, also across several records
Domain(patterns...) TLS by SNI, and HTTP/1.x and h2c by host, in one matcher
SSH(), SOCKS4(), SOCKS5() SSH clients that speak first, SOCKS requests and greetings
PostgreSQL(), MQTT(), RDP() Database, MQTT and Remote Desktop clients
OpenVPN(), XMPP(), DNS() OpenVPN over TCP, XMPP streams, DNS over TCP
HTTP2Preface() The h2c connection preface alone
Silent(d) Clients that sent nothing for d, as server-first protocols
RemoteIP(prefixes...), RemoteIPFunc(fn) Client addresses, from a fixed or a changing list
LocalIP(prefixes...), LocalIPFunc(fn) The address the client connected to
LocalPort(ports...) The port the client connected to
AnyBytes(), Always() Any client that sent a byte; every connection, unread
And, Or, Not Combinations, nested in any way
MatcherFunc, Named(name, m) Your own logic, with a description for Snapshot
Filters of Filters
HTTP Host, HostRegexp, Path, PathPrefix, PathRegexp, Method, Header, HeaderRegexp, Query, WebSocket
TLS SNI, SNIRegexp, ALPN, MinTLSVersion, fingerprint.MatchJA4, fingerprint.MatchJA3
  • Host patterns are those of nginx and Envoy: an exact name; *.example.com, any name below example.com at any depth (a.b.example.com too) but not example.com itself; .example.com, example.com and every name below it; *, any name; and "", a hello or request without a name. No other wildcards exist: *a.example.com, api-*.example.com and a.*.com are refused: hostmatch.CheckPattern reports them, and Host, SNI, Domain, hostmatch.NewSet and hostmatch.Map.Set panic on them, so check patterns from configurations first; ParseMatcher and httproute.Build return errors. Note that a wildcard certificate covers one level only: *.example.com routes a.b.example.com but a certificate for *.example.com does not cover it. Names compare case-insensitively and without a trailing dot, and names with bytes that no host name has, such as @ or any non-ASCII byte, match nothing.
  • Paths are decoded and resolved as servers resolve them, so /public/../admin/ is /admin/, a path with a control character once decoded is ruled out, and PathPrefix("/api") matches /api and /api/v1 but not /apis.
  • Each protocol is parsed once per connection, incrementally, however many routes look at it.
  • Address matchers and Silent decide without bytes, which routes protocols in which the server speaks first. A matcher of your own that waits for silence implements Silencer and reads Input.Elapsed.

A matcher of your own reads what is known about the connection from an Input:

// acmeTLS matches TLS-ALPN-01 challenges of an ACME certificate authority.
var acmeTLS = portmux.MatcherFunc(func(in *portmux.Input) portmux.Result {
	hello, res := in.ClientHello()
	if res != portmux.Match {
		return res // NeedMore until the hello is complete, NoMatch for other protocols
	}
	if slices.Contains(hello.ALPN, "acme-tls/1") {
		return portmux.Match
	}
	return portmux.NoMatch
})

Matchers return NeedMore until they can decide, and their decisions must be final: a longer input must get the same answer. They must not block. A parser of your own can keep its state between calls on one connection with Input.SetValue and Input.Value, as the built-in parsers do.

Combining Conditions

func combine(m *portmux.Mux, office netip.Prefix) {
	// Every subdomain except two, and nothing under /internal/.
	m.Listen(portmux.HTTP1(
		portmux.Host("*.example.com"),
		portmux.NoneOf(portmux.Host("admin.example.com", "db.example.com"), portmux.PathPrefix("/internal/")),
	))
	// (api.example.com AND /v1/) OR status.example.com.
	m.Listen(portmux.HTTP1(portmux.AnyOf(
		portmux.AllOf(portmux.Host("api.example.com"), portmux.PathPrefix("/v1/")),
		portmux.Host("status.example.com"),
	)))
	// The admin site over TLS 1.2 or newer, from the office only.
	m.Listen(portmux.And(
		portmux.RemoteIP(office),
		portmux.TLS(portmux.SNI("admin.example.com"), portmux.MinTLSVersion(tls.VersionTLS12)),
	))
}
Level OR AND NOT
Values of one filter or address matcher Host("a", "b"), RemoteIP(p1, p2)
Filters of one protocol AnyOf the filter list, AllOf NoneOf
Matchers of any kind the route's matcher list, Or And Not

NoneOf excludes within a protocol: HTTP1(NoneOf(Host("a"))) matches HTTP requests for other hosts, while Not(HTTP1(Host("a"))) also matches everything that is not HTTP.

Routes

// setup adds a block list, a route, a reject route and a fallback at once.
func setup(m *portmux.Mux, blocked []netip.Prefix) error {
	return m.Batch(func(b *portmux.Batch) error {
		for _, cfg := range []portmux.RouteConfig{
			{Name: "blocklist", Priority: 100, Reject: true, Matchers: []portmux.Matcher{portmux.RemoteIP(blocked...)}},
			{Name: "admin", Priority: 50, Matchers: []portmux.Matcher{portmux.Domain("admin.example.com")}},
			{Name: "web", Matchers: []portmux.Matcher{portmux.HTTP1(), portmux.TLS()}, MaxConns: 10000},
			{Name: "default", Fallback: true},
		} {
			if _, err := b.Add(cfg); err != nil {
				return err
			}
		}
		return nil
	})
}

// moveAdmin changes a route while serving; its listener keeps running.
func moveAdmin(m *portmux.Mux, host string) error {
	return m.Route("admin").SetMatchers(portmux.Domain(host))
}
  • A Reject route closes what it matches; with address matchers it does so before reading. A Fallback route takes, after every other route, what they all ruled out and what stayed undecided until the sniff timeout.
  • Matchers rule out what they cannot parse or find ambiguous, such as a request with two Host fields or a path that servers resolve differently, so a reject route does not see it and later routes may take it. Where reject routes guard the others, list what is allowed rather than what is not, and make the fallback a reject route too.
  • MaxConns limits the connections a route has open at once, and DispatchTimeout and MaxQueued replace the entry's dispatch timeout and queue limit for a route whose server is slower to accept than the others.
  • Routes can be added, changed with SetMatchers, SetPriority, SetEntries, SetMaxConns, SetDispatchTimeout and SetMaxQueued, and removed with Close at any time. Batch applies several changes at once, and Batch.Routes previews the order. Each change rebuilds the routing table, so make many changes, such as loading thousands of routes, in one Batch.
  • Undecided connections use the current routes for every decision; connections waiting for a removed route's Accept are matched again.

Entries

An entry names a group of listeners, so that ports and the services behind them are set up apart: each listener serves an entry, and each route names the entries it is offered on.

func serveEntries(m *portmux.Mux) error {
	_, err := m.Add(portmux.RouteConfig{Name: "shop", Entries: []string{"web", "web-alt"},
		Matchers: []portmux.Matcher{portmux.Domain("shop.example.com")}})
	if err != nil {
		return err
	}
	// A dedicated port: each connection is handed over before any read.
	_, err = m.Add(portmux.RouteConfig{Name: "tunnel-9000", Entries: []string{"tcp-9000"},
		Matchers: []portmux.Matcher{portmux.Always()}})
	if err != nil {
		return err
	}
	// The public port gets stricter limits than the others.
	m.Entry("web").SetOptions(portmux.WithSniffTimeout(5*time.Second), portmux.WithBanPerClient(10, time.Minute, time.Hour))

	for entry, addr := range map[string]string{"web": ":443", "web-alt": ":8443", "tcp-9000": ":9000"} {
		ln, err := net.Listen("tcp", addr)
		if err != nil {
			return err
		}
		go m.Entry(entry).Serve(ln)
	}
	return nil
}
  • A route without entries applies to every entry, which suits block lists. Each entry has its own matching order and fallback; routes of other entries are never asked.
  • Route.SetEntries moves a service to other ports without touching a listener, and closing a listener touches no route.
  • Entry.SetOptions gives an entry options of its own on top of the Mux's, and ResetOptions drops them. An entry with its own per-client rate limit or ban rule counts its clients apart; a ban applies to every entry.
  • Input.Entry and Conn.Entry name the entry, whatever a PROXY header says.

Choosing Routes in Code

A resolver route picks the target route itself, as one rule ordered by priority among the others:

// tunnels binds host names to tunnel routes, which have no matchers and are
// reached only through the name table.
type tunnels struct {
	m     *portmux.Mux
	hosts hostmatch.Map[*portmux.Route]
}

func newTunnels(m *portmux.Mux) (*tunnels, error) {
	t := &tunnels{m: m}
	_, err := m.Add(portmux.RouteConfig{Name: "tunnels", Priority: 10, Resolve: portmux.ResolveDomain(&t.hosts)})
	return t, err
}

func (t *tunnels) add(pattern string) (*portmux.Route, error) {
	r, err := t.m.Add(portmux.RouteConfig{Name: "tunnel:" + pattern})
	if err == nil {
		t.hosts.Set(pattern, r)
	}
	return r, err
}

// resolveSites keeps an HTTPS and an HTTP route per name, and falls back to a
// wider pattern when a name has none for the protocol.
func resolveSites(sites *hostmatch.Map[[2]*portmux.Route]) portmux.ResolveFunc {
	return portmux.ResolveHosts(sites, func(in *portmux.Input, _ string, s [2]*portmux.Route) (*portmux.Route, bool) {
		if _, res := in.ClientHello(); res == portmux.Match {
			return s[0], s[0] != nil
		}
		return s[1], s[1] != nil
	})
}
  • A ResolveFunc sees everything about the connection and returns a route, NeedMore or NoMatch. Its matchers, if any, are conditions checked first.
  • hostmatch.Map looks a name up by the most specific pattern: the exact name, then .name for the name itself, then the wildcards by the length of their suffix (*. before . on a tie), then *. LookupFunc and Matches fall back to wider patterns for policies of your own. Lookups take no lock, and allocate nothing for lowercase names and those that Input prepared. Set, Delete and Edit, which applies many changes at once, publish an immutable hostmatch.Snapshot; Load returns the current one.
  • ResolveHosts and ResolveDomain route TLS, HTTP/1.x and h2c by the name the client asks for, and protocols of your own by the name a matcher sets with Input.SetRequestedName. Paths are for the HTTP server behind the route.
  • To replace the route of a name while serving, add the new route, point the name table to it, then close the old one: ResolveHosts passes closed routes over, so no connection reaches one.
  • Mux.Upsert and Batch.Upsert add or change routes by name, keeping the listener of a route that stays, which suits reloading a configuration: upsert the routes it has, then remove the routes it no longer has. SetHandler and SetResolve change those of a route in place.

Rules as Text

// loadRule adds a route kept as text, as in a configuration file.
func loadRule(m *portmux.Mux, name, text string, office portmux.Matcher) error {
	names := &portmux.Names{Matchers: map[string]portmux.Matcher{"office": office}}
	matcher, err := portmux.ParseMatcher(text, names) // a *portmux.ParseError tells where it failed
	if err != nil {
		return err
	}
	_, err = m.Add(portmux.RouteConfig{Name: name, Matchers: []portmux.Matcher{matcher}})
	return err
}

ParseMatcher reads what matchers print, as in And(office, TLS(SNI("*.example.com"), MinTLSVersion(1.2))), so the matchers of routes can be stored and read back, next to the other settings of their RouteConfig. Names supplies your own matchers and filters, also with arguments; fpnames.Register (package fingerprint/fpnames) adds JA4("...") and JA3("...").

Delivery

// serveTunnel serves connections in the goroutine that matched them,
// without an accept loop.
func serveTunnel(m *portmux.Mux, backend string) (*portmux.Route, error) {
	return m.Add(portmux.RouteConfig{
		Matchers: []portmux.Matcher{portmux.Prefix("TUNNEL/1\n")},
		Handler: func(c *portmux.Conn) {
			defer c.Close()
			b, err := net.Dial("tcp", backend)
			if err != nil {
				return
			}
			defer b.Close()
			go io.Copy(b, c)
			io.Copy(c, b)
		},
	})
}
  • A route delivers to Accept, or to its Handler, which needs no accept loop and scales best for a busy route.
  • A Conn carries what was parsed: ClientHello, HTTPRequest, HTTP2Request, RequestedName, ProxyHeader, the values that your matchers stored with Input.SetValue (Conn.Value), Entry and Route. It keeps half-close and the fast copy paths of the underlying connection.
  • A panic in a matcher, resolver, PROXY policy or handler closes only its connection and is reported as a *PanicError.
  • Serve runs for any number of listeners, and ServeConn routes a connection obtained elsewhere, without the admission of Serve: limits, bans and rates apply to connections that come through a net.Listener passed to Serve. Shutdown waits for pending connections to be routed; Close stops at once, after which Add and Batch return net.ErrClosed. Neither affects delivered connections.

A route is a net.Listener, so TLS can be terminated on it and what it carries routed again by a second Mux, for example SOCKS and HTTP proxies inside TLS on the same port as plain ones:

// serveInsideTLS routes the plain connections of l, and those inside TLS
// with cert by the same routes.
func serveInsideTLS(l net.Listener, cert tls.Certificate, proxies func(*portmux.Mux)) error {
	outer, inner := portmux.New(), portmux.New()
	proxies(outer)
	proxies(inner)
	secure := outer.Listen(portmux.TLS())
	go inner.Serve(tls.NewListener(secure, &tls.Config{Certificates: []tls.Certificate{cert}}))
	return outer.Serve(l)
}

Connections of the inner Mux keep the client address of the outer one, including one from a PROXY header. An http.Server behind the inner Mux gets *portmux.Conns rather than *tls.Conns, so Request.TLS is nil; take the state from the TLS connection under the Conn:

type tlsStateKey struct{}

// tlsState puts the TLS state of a connection inside TLS in its requests'
// context, for handlers that need it, such as to set HSTS or Secure cookies.
func tlsState(ctx context.Context, c net.Conn) context.Context {
	if pc, ok := c.(*portmux.Conn); ok {
		if tc, ok := pc.NetConn().(*tls.Conn); ok {
			return context.WithValue(ctx, tlsStateKey{}, tc.ConnectionState())
		}
	}
	return ctx
}

// Then: srv := &http.Server{Handler: h, ConnContext: tlsState}, and in h,
// state, isTLS := r.Context().Value(tlsStateKey{}).(tls.ConnectionState).

PROXY Protocol

// behindLoadBalancer expects PROXY headers on the entry "lb", from the
// balancer's subnet only; TrustPeers(lb) does it for every entry.
func behindLoadBalancer(lb netip.Prefix) *portmux.Mux {
	trusted := portmux.TrustPeers(lb)
	return portmux.New(portmux.WithProxyProtocol(func(entry string, peer, local net.Addr) proxyproto.Policy {
		if entry != "lb" {
			return proxyproto.Ignore
		}
		return trusted(entry, peer, local)
	}))
}

Headers of version 1 and 2 are removed before matching, and their addresses are what address matchers and the Conn see. Allow them only from trusted peers. Per-client limits and bans apply to the sources in the headers; a trusted peer is not banned for its own connections without a valid header, so that a misconfigured balancer is not banned with every client behind it.

Options

func newPublicMux() *portmux.Mux {
	return portmux.New(
		portmux.WithSniffTimeout(5*time.Second),
		portmux.WithMaxPendingPerClient(32),
		portmux.WithRateLimitPerClient(20, 40),
		portmux.WithBanPerClient(10, time.Minute, 10*time.Minute),
		portmux.WithObserver(func(ev portmux.Event) {
			if ev.Err != nil {
				log.Printf("%s %s: %v", ev.Entry, ev.Remote, ev.Err)
			}
		}),
	)
}

// tighten lowers the limits while serving and returns the new settings.
func tighten(m *portmux.Mux) portmux.Config {
	m.SetOptions(portmux.WithMaxPendingPerClient(4), portmux.WithRateLimitPerClient(2, 4))
	return m.Config()
}
Option Default Effect Per entry
WithSniffTimeout(d) 10s Time until a route matches, not counting a wait for a pending slot yes
WithDispatchTimeout(d) 5s Time a matched connection waits for Accept yes
WithMaxSniffBytes(n) 16 KiB Bytes buffered for matching yes
WithMaxPending(n) 4096 Connections being matched; at the limit the oldest undecided is evicted
WithMaxPendingPerClient(n) none Undelivered connections per client yes
WithRateLimitPerClient(r, b) none New connections per second per client yes
WithRateLimitPerListener(r, b) none New connections per second per listener yes
WithBanPerClient(n, w, d) none Bans for d a client with n failed connections within w yes
WithMaxQueued(n) 1024 Matched connections waiting for one route's Accept yes
WithObserver(fn) none Called with an Event for every connection delivered or closed
WithProxyProtocol(policy) none PROXY protocol v1/v2 per entry and peer
WithClientPrefix(v4, v6) 32, 64 Networks counted as one client by the per-client limits and bans
WithClientRecords(n, full) 65536, fail open Clients each rate and ban table holds (negative: no limit), and what a full one does: FullFailOpen, FullFailClosed or FullEvictOldest
WithClock(c) system Time of bans, rate limits and close events; timeshim.Fake in tests
WithCloseEvents(on) off An Event when a delivered connection closes, with duration and bytes
  • SetOptions changes options while serving; Config reads them back, and Entry.Config the settings of an entry.
  • Clients are IPv4 addresses and IPv6 /64 networks, or the networks of WithClientPrefix, of the TCP peer, or of the source in the PROXY header of a peer that WithProxyProtocol lets send one, so that a load balancer is not limited or banned for its clients. Failed connections that count toward bans matched no route, timed out, hit a reject route or sent an invalid PROXY header or none where one is required; Mux.Ban, BanPrefix, Unban and UnbanPrefix act by hand; Unban lifts the bans of every network that holds the address, such as a /24 banned under a shorter prefix.
  • A matched connection waiting for Accept holds no pending slot: the queue of its route, WithMaxQueued and RouteConfig.MaxQueued, and the dispatch timeout bound those. In a RouteConfig, a zero DispatchTimeout or MaxQueued keeps the entry's setting and a negative one removes the limit, while a zero MaxConns means no limit.
  • Entry.ResetOptions drops one or all of an entry's settings, Mux.Entries lists the entries in use, which catches a misspelt name, and Config.Options turns settings read back into options again.
  • An Event carries the name the client asked for, what matchers parsed and stored (Event.Value) and the TCP peer, for logs and fingerprints, and reports with Banned the failure that banned its client. With WithCloseEvents(true) the observer also hears when a delivered connection is closed, how long it was open and how many bytes it carried.
  • Rejected connections are reported with ErrNoMatch, ErrRefused, ErrSniffTimeout, ErrDispatchTimeout, ErrEvicted, ErrPendingLimit, ErrRateLimited, ErrBanned, ErrQueueFull, ErrConnLimit, ErrRouteClosed, ErrEntryMismatch, a *PanicError, the proxyproto errors or read errors. Route configurations that are not valid fail with errors that wrap ErrInvalidRoute.

Status

func printStatus(m *portmux.Mux) {
	snap := m.Snapshot()
	for _, r := range snap.Routes {
		fmt.Printf("%-12s prio=%-4d matched=%d open=%d %s\n", r.Name, r.Priority, r.Matched, r.Open, strings.Join(r.Matchers, " | "))
	}
	for _, l := range snap.Listeners {
		fmt.Printf("%-8s %s accepted=%d rejected=%d\n", l.Entry, l.Addr, l.Stats.Accepted, l.Stats.Rejected)
	}
}

Snapshot returns the routes in matching order, the listeners and the counters at one moment, and Stats breaks rejected connections down by reason. Mux.Bans lists the banned clients.

Security

Threat Handling
Scans, garbage, data too short and then silence Ruled out at the first impossible byte; sniff timeout; bans
Floods of idle or slow connections The pending limit, evicting the oldest undecided connection
Floods from one client or from many Rate and pending limits per client, rate limit per listener
Heads in tiny pieces, many TLS records, HPACK bombs Incremental parsing; bounded head and header sizes
Ambiguous requests and names Duplicate Host headers or SNI names, folded headers, control characters and names with @ fail
Spoofed client addresses PROXY headers only from peers the policy trusts
A stalled server on one route Queue limit and dispatch timeout per route
Known scanner TLS libraries A reject route with TLS(fingerprint.MatchJA4(...))

portmux sees established TCP connections only: SYN floods are for the kernel, and delivered connections are the servers' to limit.

HTTP Routing

httproute routes the requests on the connections that routes hand over, as a reverse proxy does: by host, path, method and header fields, to a backend that your dial function reaches, to a redirect or to a fixed response.

// serveSites routes the HTTP and HTTPS connections of m by request.
func serveSites(m *portmux.Mux, config *tls.Config, dial httproute.DialFunc) (*httproute.Router, error) {
	headers, err := httprewrite.ParseRules(`
X-Real-IP: ${remote_addr}
X-Forwarded-Proto: ${scheme}
`, httproute.Vars())
	if err != nil {
		return nil, err
	}
	table, err := httproute.Build(httproute.Config{
		Upstreams: []httproute.Upstream{{Name: "app", Dial: dial, ResponseHeaderTimeout: 30 * time.Second}},
		Routes: []httproute.Route{
			{Name: "api", Hosts: []string{"*.example.com"}, Path: "/api", RedirectHTTPS: &httproute.HTTPSRedirect{},
				Proxy: &httproute.Proxy{Upstream: "app", ReplacePath: "/"}, RequestHeaders: headers},
			{Name: "old", Path: "/old", Redirect: &httproute.Redirect{
				To: httprewrite.MustCompile("https://${host}/new/${path_rest}", httproute.Vars()), Status: 301}},
			{Name: "health", Path: "/healthz", Respond: &httproute.Respond{Body: []byte("ok")}},
		},
		ErrorPages: map[int]httproute.ErrorPage{502: {Body: []byte("<h1>Backend down</h1>")}},
	})
	if err != nil {
		return nil, err
	}
	router := httproute.New(httproute.Options{})
	if err := router.Update(table); err != nil {
		return nil, err
	}
	_, err = m.Add(portmux.RouteConfig{Name: "https", Matchers: []portmux.Matcher{portmux.TLS()},
		Handler: func(c *portmux.Conn) { _ = router.ServeConn(tls.Server(c, config)) }})
	if err != nil {
		return nil, err
	}
	_, err = m.Add(portmux.RouteConfig{Name: "http", Matchers: []portmux.Matcher{portmux.HTTP1()},
		Handler: func(c *portmux.Conn) { _ = router.ServeConn(c) }})
	return router, err
}

Of the routes whose host patterns match the request, and whose Methods and Headers fit it, the router takes:

  1. a route whose Exact path is the request's path;
  2. else the first route whose PathRegexp (Go regexp, linear time) matches it;
  3. else the route with the longest Path prefix, by whole segments: /api takes /api, /api/v1 and /api;v=1 but not /apix; /api/ takes only paths below it; /api* is a prefix of bytes and also takes /apix.

Within a level, the most specific host pattern wins, as hostmatch.Map ranks them: the exact name, then the longer wildcard suffix (*.api.example.com before *.example.com), then *; then the route listed first. Hosts: ["*"] is the same as no Hosts: it takes requests without a host too. PathRegexp is not anchored, as nginx's ~ is not: /admin matches /public/admin-ui, so write ^/admin$ for whole paths.

Routes Request Route
a.example.com /, *.example.com /api a.example.com/api/x *.example.com /api
a.example.com /api, *.example.com /api a.example.com/api a.example.com /api
.example.com /, * / example.com/ .example.com /
*.example.com = /login, a.example.com /login a.example.com/login *.example.com = /login
a.example.com ~ ^/u/\d+$, *.example.com ~ ^/u/ a.example.com/u/x *.example.com ~ ^/u/
* /img*, * / x.org/img2/a.png * /img*
a.example.com / with Methods: POST, * / GET a.example.com/ * /

Paths are decoded and resolved as httphead.CleanPath does: requests whose path servers read differently, or that holds a control character once decoded, get 400, and so do hosts that are not ASCII host names. The backend gets the path the route was chosen by, with the client's escapes where they fit, unless Proxy.SendRawPath is set. CaseInsensitivePath serves backends that ignore case. TLS filters on whether the request came over TLS, by the connection or a trusted proxy alone. Build refuses routes that match the same requests as one before them for a host, and routes that one before them hides entirely.

  • Build checks a Config and returns an immutable Table; Table.With adds, replaces and removes routes and upstreams by name and returns a new Table, compiling only the host patterns it touches, so one change is cheap in a table of any size. Update replaces the table while serving, and requests keep the table they were matched with. Upstreams whose settings stay the same keep their idle connections.
  • A DialFunc gets the request's context and a DialInfo with the route, host and client; it is where load balancing goes. A *StatusError it returns sets the status, such as 503 for a backend that is offline; other errors give 502 and timeouts 504. A connection serves later requests of the upstream unless DisableKeepAlives is set.
  • Proxy.Pick chooses a backend per request, such as a member of a group with sticky sessions, and returns a key for it: the upstream pools connections per key, and Dial gets it as DialInfo.Key. A key keeps memory only while it has connections; above Upstream.MaxKeys (1024) the idle connections of the least recently used key are closed. A *StatusError from Pick sets the status as from a DialFunc.
  • Header rules, redirect targets, Proxy.PathTemplate and the ${...} of error pages are httprewrite variables, its own and those of Vars: route, route_path, path_rest, match_1 to match_9 (the groups of a PathRegexp) and request_id. Error pages escape values for HTML. A rule on Host rewrites the host; without one the client's goes on. Forwarding fields that clients send are dropped; rules add them, with the client that Config.Resolver finds behind trusted proxies.
  • Upstream.Addr alone is enough to dial a backend over TCP. With TLS, the server name is ServerName, else the name in Addr, else the outgoing Host. HTTP2 speaks HTTP/2 by ALPN over TLS and h2c without it, upgrades staying on HTTP/1.1; ProxyProtocol sends a PROXY header of version 1 or 2 with the client's address on each connection.
  • Route.BasicAuth checks Basic credentials against hashes from HashPassword (PBKDF2-HMAC-SHA256 in a self-describing form), or a Verify function of yours. Verified credentials are remembered for CacheTTL, at most CacheSize of them (1024; DisableCache remembers none), the least recently used dropped first, until the table is replaced; at most one hash per CPU runs at a time. Allow is asked for every request with valid credentials, remembered ones too, so that an account that expires or is disabled is refused at once.
  • Upgrades are limited to Route.Upgrades, websocket by default; other Upgrade fields and HTTP2-Settings are removed, so that no h2c upgrade gets past the routes. Plain CONNECT gets 405; WebSockets over HTTP/2 (extended CONNECT) are routed by their path and passed to the backend over HTTP/1.1. net/http accepts them when the program starts with GODEBUG=http2xconnect=1.
  • Config.AbortNoRoute closes the connection, or resets the HTTP/2 stream, instead of answering 404 when no route matches.
  • ${request_id} is the X-Request-Id of a trusted proxy, else random.
  • Route.UpgradeIdleTimeout closes upgraded connections, such as WebSockets, that carry nothing for a while.
  • Settings: the zero value of a field selects its default, a safe bound for timeouts and limits unless the field says otherwise; a negative timeout means no timeout, as for http.Server.IdleTimeout; other negative values are an invalid config unless the field gives them a meaning. Upstream.MaxIdleConns and IdleConnTimeout default to 64 and 90 s, unlike http.Transport, where 0 means no limit. The zero value is no bound for Upstream.ResponseHeaderTimeout, Route.UpgradeIdleTimeout and Route.MaxRequestBody.
  • Hop-by-hop fields are removed; upgrades such as WebSocket, trailers, Expect: 100-continue and streaming responses pass through. With "h2" in the TLS config's NextProtos, clients may use HTTP/2.
  • ServeConn serves a connection that a route hands over, plain or as a *tls.Conn; Serve serves a listener such as a route; the Router is also an http.Handler. A connection that wraps a TLS connection and has a NetConn method, such as a *portmux.Conn of a nested Mux, gives its requests the TLS state. Route.Wrap adds authentication, limits or metrics of your own, and Options.Observer reports every request.
  • Shutdown and Close end upgraded connections too and wait for the requests in progress to return.

Without a Mux

Function Use
Peek(c, m, sniffOpts...), PeekAny(c, ms, sniffOpts...) Sniff one connection, and tell which matcher took it
NewPeeker(ms, sniffOpts...), Peeker.Peek(c) PeekAny with its matchers prepared once
tlshello.Parse, httphead.Parse, httphead.ParseHTTP2 Parse the first bytes of a connection
httphead.CleanPath, httphead.HasPathPrefix Resolve request paths and compare them as routes do
tlshello.Scanner, httphead.Scanner, httphead.HTTP2Scanner Parse as bytes arrive
fingerprint.JA4, fingerprint.JA3 Fingerprint a client's TLS library
hostmatch.Set, hostmatch.Map, ipmatch.Set Match host names and IP addresses as the routes do
NewInput, ParseMatcher Run matchers on bytes of your choice; read them from text

Parsers return io.ErrUnexpectedEOF while the bytes are incomplete and ErrInvalid when they are not of their protocol.

Limits

  • Protocols in which the server speaks first are routed by Silent or by address, and h2c clients that wait for the server's SETTINGS by HTTP2Preface.
  • TLS is told apart only by its cleartext ClientHello; with Encrypted Client Hello the SNI is the outer name. Nest a second Mux to route inside TLS.
  • UDP is out of scope.

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() }

Index

Examples

Constants

View Source
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

View Source
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 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) Add

func (b *Batch) Add(cfg RouteConfig) (*Route, error)

Add adds a route.

func (*Batch) Remove

func (b *Batch) Remove(r *Route) error

Remove removes r and closes its listener once the batch is applied.

func (*Batch) Route

func (b *Batch) Route(name string) *Route

Route returns the route with the given name, including changes made in this batch, or nil.

func (*Batch) Routes

func (b *Batch) Routes() []*Route

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

func (b *Batch) SetDispatchTimeout(r *Route, d time.Duration) error

SetDispatchTimeout changes the dispatch timeout of r; see RouteConfig.DispatchTimeout.

func (*Batch) SetEntries

func (b *Batch) SetEntries(r *Route, entries ...string) error

SetEntries limits r to connections of the entries, or lets it apply to every entry when none are given.

func (*Batch) SetHandler

func (b *Batch) SetHandler(r *Route, handler func(*Conn)) error

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

func (b *Batch) SetMatchers(r *Route, matchers ...Matcher) error

SetMatchers replaces the matchers of r.

func (*Batch) SetMaxConns

func (b *Batch) SetMaxConns(r *Route, n int) error

SetMaxConns changes the limit of open connections of r; see RouteConfig.MaxConns. Open connections over a lowered limit stay open.

func (*Batch) SetMaxQueued

func (b *Batch) SetMaxQueued(r *Route, n int) error

SetMaxQueued changes the limit of queued connections of r; see RouteConfig.MaxQueued.

func (*Batch) SetPriority

func (b *Batch) SetPriority(r *Route, priority int) error

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

func (c Config) Options() []Option

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

func Peek(c net.Conn, m Matcher, opts ...PeekOption) (*Conn, error)

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)
		}()
	}
}

func PeekAny

func PeekAny(c net.Conn, matchers []Matcher, opts ...PeekOption) (*Conn, int, error)

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

func (c *Conn) ClientHello() *tlshello.Hello

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

func (c *Conn) Close() error

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

func (c *Conn) CloseRead() error

CloseRead shuts down the reading side when the underlying connection supports it, and returns errors.ErrUnsupported otherwise.

func (*Conn) CloseWrite

func (c *Conn) CloseWrite() error

CloseWrite shuts down the writing side when the underlying connection supports it, and returns errors.ErrUnsupported otherwise.

func (*Conn) Entry

func (c *Conn) Entry() string

Entry returns the name of the entry the connection came through; see Mux.Entry.

func (*Conn) HTTP2Request

func (c *Conn) HTTP2Request() *httphead.Request

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

func (c *Conn) HTTPRequest() *httphead.Request

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

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the PROXY header's destination address when one was parsed, and the connection's local address otherwise.

func (*Conn) NetConn

func (c *Conn) NetConn() net.Conn

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) Read

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

Read reads the replayed bytes first, then from the client.

func (*Conn) ReadFrom

func (c *Conn) ReadFrom(r io.Reader) (int64, error)

ReadFrom copies r to the connection, so io.Copy can still use the underlying connection's fast paths.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the PROXY header's source address when one was parsed, and the connection's remote address otherwise.

func (*Conn) RequestedName

func (c *Conn) RequestedName() string

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) Route

func (c *Conn) Route() *Route

Route returns the route that matched the connection.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines of the underlying connection.

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline of the underlying connection. Reads of replayed bytes do not block and ignore it.

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline of the underlying connection.

func (*Conn) Unread

func (c *Conn) Unread() []byte

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.

func (*Conn) Value

func (c *Conn) Value(key any) any

Value returns the value that a matcher or resolver stored under key with Input.SetValue while the connection was matched, or nil, so that what a parser of your own found reaches the server of the route.

func (*Conn) Write

func (c *Conn) Write(p []byte) (int, error)

Write writes to the client.

func (*Conn) WriteTo

func (c *Conn) WriteTo(w io.Writer) (int64, error)

WriteTo writes the replayed bytes and then copies the rest of the stream to w, so io.Copy can still use the underlying connection's fast paths.

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

func (e *Entry) Config() 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) Name

func (e *Entry) Name() string

Name returns the entry's name.

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) Serve

func (e *Entry) Serve(ln net.Listener) error

Serve serves ln as a listener of the entry; see Mux.Serve.

func (*Entry) ServeConn

func (e *Entry) ServeConn(c net.Conn) error

ServeConn routes c as a connection of the entry; see Mux.ServeConn.

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.
	Err error
	// Elapsed is the time from taking the connection, as in
	// WithSniffTimeout, to the decision, by the monotonic clock, whose ticks are coarse on some systems such as
	// Windows.
	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.
	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.

func (Event) Value

func (e Event) Value(key any) any

Value returns the value that a matcher or resolver stored under key with Input.SetValue while the connection was matched, or nil, as Conn.Value does.

type Filter

type Filter[T any] interface {
	Match(v T) bool
}

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.

func AllOf

func AllOf[T any](filters ...Filter[T]) Filter[T]

AllOf passes when every filter passes, and when there are none.

func AnyOf

func AnyOf[T any](filters ...Filter[T]) Filter[T]

AnyOf passes when at least one filter passes.

func NoneOf

func NoneOf[T any](filters ...Filter[T]) Filter[T]

NoneOf passes when no filter passes, which excludes what they describe, as in HTTP1(Host("*.example.com"), NoneOf(Host("admin.example.com"))).

type FilterFunc

type FilterFunc[T any] func(v T) bool

FilterFunc adapts a function to the Filter interface.

func (FilterFunc[T]) Match

func (f FilterFunc[T]) Match(v T) bool

Match calls f(v).

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

type HTTPFilter = Filter[*httphead.Request]

HTTPFilter restricts the requests accepted by HTTP1.

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

func NewInput(remote, local net.Addr) *Input

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

func (in *Input) Bytes() []byte

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

func (in *Input) ClientHello() (*tlshello.Hello, Result)

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

func (in *Input) Elapsed() time.Duration

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

func (in *Input) Entry() string

Entry returns the name of the entry the connection came through; see Mux.Entry.

func (*Input) Final

func (in *Input) Final() bool

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

func (in *Input) HTTP2Request() (*httphead.Request, Result)

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

func (in *Input) HTTPRequest() (*httphead.Request, Result)

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

func (in *Input) LocalAddr() net.Addr

LocalAddr returns the address the client connected to, taken from the PROXY protocol header when one was parsed.

func (*Input) PeerAddr

func (in *Input) PeerAddr() net.Addr

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

func (in *Input) RDPCookie() (string, Result)

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

func (in *Input) RemoteAddr() net.Addr

RemoteAddr returns the client address, taken from the PROXY protocol header when one was parsed.

func (*Input) RequestedName

func (in *Input) RequestedName() (string, Result)

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

func (in *Input) SetBytes(data []byte, final bool)

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

func (in *Input) SetEntry(name string)

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

func (in *Input) SetRequestedName(name string)

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

func (in *Input) SetValue(key, value any)

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.

func (*Input) Value

func (in *Input) Value(key any) any

Value returns the value that SetValue stored under key for this connection, or nil.

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

type Matcher interface {
	Match(in *Input) Result
}

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 And

func And(matchers ...Matcher) Matcher

And matches when every matcher matches. It decides NoMatch as soon as one of them does.

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

func Domain(patterns ...string) Matcher

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

func LocalIP(prefixes ...netip.Prefix) Matcher

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

func LocalIPFunc(contains func(netip.Addr) bool) Matcher

LocalIPFunc is RemoteIPFunc for the local address, as LocalIP is RemoteIP.

func LocalPort

func LocalPort(ports ...uint16) Matcher

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

func Named(name string, m Matcher) Matcher

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

func Not(m Matcher) Matcher

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

func Or(matchers ...Matcher) Matcher

Or matches when any matcher matches. A route already accepts any of its matchers; Or is for nesting inside And and Not.

func ParseMatcher

func ParseMatcher(text string, names *Names) (Matcher, error)

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

so that routes can be kept in configuration files and databases: every built-in matcher and filter prints text that ParseMatcher turns into an equal matcher, except RemoteIPFunc and LocalIPFunc, whose functions have no text; name them in names to keep them as text. Strings are Go string literals; prefixes, ports, durations and versions are written bare. names, which may be nil, supplies the matchers and filters of your own.

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 Prefix

func Prefix(prefixes ...string) Matcher

Prefix matches connections whose first bytes equal one of the prefixes.

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

func Regexp(re *regexp.Regexp, n int) Matcher

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

func RemoteIP(prefixes ...netip.Prefix) Matcher

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

func RemoteIPFunc(contains func(netip.Addr) bool) Matcher

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, as OpenSSH does. Use Silent for clients that wait for the server.

func Silent

func Silent(d time.Duration) Matcher

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

func TLS(filters ...TLSFilter) Matcher

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, and rules out a stream header longer than 2 KiB.

type MatcherFunc

type MatcherFunc func(in *Input) Result

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) Match

func (f MatcherFunc) Match(in *Input) Result

Match calls f(in).

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 New

func New(opts ...Option) *Mux

New returns a Mux without listeners or routes.

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

func (m *Mux) Ban(client netip.Addr, d time.Duration)

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

func (m *Mux) BanPrefix(network netip.Prefix, d time.Duration)

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

func (m *Mux) Bans() []Ban

Bans returns the clients that are banned now, automatically or with Ban or BanPrefix, in no particular order.

func (*Mux) Batch

func (m *Mux) Batch(fn func(b *Batch) error) error

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

func (m *Mux) Close() error

Close closes the listeners and every connection that was not delivered yet. Routes then return net.ErrClosed from Accept. Delivered connections are not affected. It returns the first error from closing a listener.

func (*Mux) Config

func (m *Mux) Config() 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

func (m *Mux) Entries() []string

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) Entry

func (m *Mux) Entry(name string) *Entry

Entry returns the handle of the entry with the given name.

func (*Mux) Listen

func (m *Mux) Listen(matchers ...Matcher) *Route

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) Route

func (m *Mux) Route(name string) *Route

Route returns the route with the given name, or nil.

func (*Mux) Routes

func (m *Mux) Routes() []*Route

Routes returns the current routes in matching order, fallback routes last.

func (*Mux) Serve

func (m *Mux) Serve(ln net.Listener) error

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))
}

func (*Mux) ServeConn

func (m *Mux) ServeConn(c net.Conn) error

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

func (m *Mux) SetOptions(opts ...Option)

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

func (m *Mux) Shutdown(ctx context.Context) error

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

func (m *Mux) Snapshot() 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) Stats

func (m *Mux) Stats() Stats

Stats returns the current counters of the Mux.

func (*Mux) Unban

func (m *Mux) Unban(client netip.Addr) bool

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

func (m *Mux) UnbanPrefix(network netip.Prefix) bool

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.

func (*Mux) Upsert

func (m *Mux) Upsert(cfg RouteConfig) (*Route, error)

Upsert adds or changes the route named cfg.Name; see Batch.Upsert.

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

func WithClientPrefix(v4, v6 int) Option

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

func WithClock(c timeshim.Clock) Option

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

func WithCloseEvents(on bool) Option

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 costs an atomic addition per read and write; without it, they are not counted. It applies to connections accepted after it is set, whose close events go to the observer of that time; see WithObserver.

func WithMaxPending

func WithMaxPending(n int) Option

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

func WithObserver(fn func(Event)) Option

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 struct {
	// Value is the value passed to panic.
	Value any
	// Stack is the stack of the goroutine that panicked.
	Stack []byte
}

PanicError is reported for a connection whose matcher, resolver, PROXY protocol policy or route handler panicked: the Mux recovers, closes the connection and goes on serving the others.

func (*PanicError) Error

func (e *PanicError) Error() string

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))
}

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.

func (*Peeker) Peek

func (p *Peeker) Peek(c net.Conn) (*Conn, int, error)

Peek is PeekAny with the matchers and options of p. It panics without a connection.

type ResolveFunc

type ResolveFunc func(in *Input) (*Route, Result)

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 Result

type Result uint8

Result is the decision of a Matcher for the input seen so far.

const (
	// NoMatch means the connection does not belong to the route.
	NoMatch Result = iota
	// Match means the connection belongs to the route.
	Match
	// NeedMore means the input seen so far is not enough to decide.
	NeedMore
)

func (Result) String

func (r Result) String() string

String returns the name of the result.

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

func (r *Route) Accept() (net.Conn, error)

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

func (r *Route) AcceptConn() (*Conn, error)

AcceptConn is Accept with the concrete connection type.

func (*Route) Addr

func (r *Route) Addr() net.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

func (r *Route) Close() error

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

func (r *Route) Entries() []string

Entries returns the entries the route is limited to, or nil when it applies to every entry.

func (*Route) Fallback

func (r *Route) Fallback() bool

Fallback reports whether the route takes connections that no route matched.

func (*Route) Info

func (r *Route) Info() RouteInfo

Info returns the current state of the route.

func (*Route) Matched

func (r *Route) Matched() uint64

Matched returns how many connections the route has matched. For a reject route these are the connections it closed.

func (*Route) Matchers

func (r *Route) Matchers() []Matcher

Matchers returns the route's current matchers.

func (*Route) MaxConns

func (r *Route) MaxConns() int

MaxConns returns the route's limit of open connections, or zero.

func (*Route) Name

func (r *Route) Name() string

Name returns the route's name.

func (*Route) Priority

func (r *Route) Priority() int

Priority returns the route's current priority.

func (*Route) Reject

func (r *Route) Reject() bool

Reject reports whether the route closes the connections it matches.

func (*Route) SetDispatchTimeout

func (r *Route) SetDispatchTimeout(d time.Duration) error

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

func (r *Route) SetEntries(entries ...string) error

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

func (r *Route) SetHandler(handler func(*Conn)) error

SetHandler changes the route's handler; see Batch.SetHandler. It returns net.ErrClosed for a removed route.

func (*Route) SetMatchers

func (r *Route) SetMatchers(matchers ...Matcher) error

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

func (r *Route) SetMaxConns(n int) error

SetMaxConns changes the limit of open connections; see RouteConfig.MaxConns. It returns net.ErrClosed for a removed route.

func (*Route) SetMaxQueued

func (r *Route) SetMaxQueued(n int) error

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

func (r *Route) SetPriority(priority int) error

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))
}

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

type Silencer interface {
	Silences(add func(time.Duration))
}

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

type TLSFilter = Filter[*tlshello.Hello]

TLSFilter restricts the ClientHellos accepted by TLS.

func ALPN

func ALPN(protocols ...string) TLSFilter

ALPN accepts ClientHellos that offer at least one of the protocols.

func MinTLSVersion

func MinTLSVersion(v uint16) TLSFilter

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

func SNI(patterns ...string) TLSFilter

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.

func SNIRegexp

func SNIRegexp(re *regexp.Regexp) TLSFilter

SNIRegexp accepts ClientHellos whose server name, lowercased, matches re. ClientHellos without SNI, or with a name that has bytes that no DNS name or IP address has, never match.

type TLSFilterFunc

type TLSFilterFunc = FilterFunc[*tlshello.Hello]

TLSFilterFunc adapts a function to TLSFilter.

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", as nginx and Envoy choose virtual hosts by name: Set tells whether a name matches any pattern, and Snapshot maps patterns to values and looks names up by specificity, the exact name first and "*" last.
Package hostmatch matches host names against patterns such as "*.example.com" and ".example.com", as nginx and Envoy choose virtual hosts by name: Set tells whether a name matches any pattern, and Snapshot maps patterns to values and looks names up by specificity, the exact name first and "*" last.
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.
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.

Jump to

Keyboard shortcuts

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