netx

package module
v0.0.0-...-466b026 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 24 Imported by: 1 module, 0 packages

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

netx

Reusable Go networking helpers with no third-party dependencies; the one module they use is timeshim, an injectable clock that itself uses only the standard library.

Requires Go 1.26. Every package builds on all major Go ports, including Windows, the BSDs, js/wasm, wasip1 and Plan 9. Platform-specific features return an error matching errors.ErrUnsupported where they are not available.

Package Contents
github.com/djylb/netx conn wrappers, Relay, ConnGroup, in-memory listeners, error helpers
github.com/djylb/netx/duplex a read half and a write half as one net.Conn, with half-closes and hot swaps
github.com/djylb/netx/tlsconn bounded TLS handshakes, TLS over any dialer, certs, pins, uploaded-cert checks
github.com/djylb/netx/proxyproto PROXY protocol v1 and v2: build, decode, header-reading conn and listener
github.com/djylb/netx/transparent transparent-proxy listeners (TCP, Linux TPROXY UDP), original destinations
github.com/djylb/netx/udpflow packet sockets as datagram flow listeners, with UDP destination-aware replies
github.com/djylb/netx/socks5 SOCKS5 and SOCKS4 codec, client dialer and a configurable server
github.com/djylb/netx/httpproxy HTTP proxy server: CONNECT tunnels and request forwarding
github.com/djylb/netx/httphead HTTP/1.x head reader and parser: fields, body framing, request targets
github.com/djylb/netx/forwarded real client address behind trusted proxies: X-Forwarded-For, X-Real-IP, Forwarded
github.com/djylb/netx/httprewrite header templates and rules for reverse proxies, redirect rewriting
github.com/djylb/netx/wsconn WebSocket: handshakes, messages, stream net.Conn, permessage-deflate
github.com/djylb/netx/wsconn/wshttp WebSocket for net/http handlers, also over HTTP/2
github.com/djylb/netx/proxydial dialing through HTTP(S), SOCKS5 and SOCKS4 proxies, ALL_PROXY/NO_PROXY
github.com/djylb/netx/safedial dialing and UDP relaying limited by a destination policy, rebinding-safe
github.com/djylb/netx/memnet in-process network for tests: TCP-like streams, datagrams, faults per link

Each package depends on the standard library and timeshim. tlsconn imports crypto/tls directly, and httprewrite and wsconn/wshttp bring it in through net/http. Programs that use proxydial for cleartext proxies can omit TLS dependencies.

Configure servers and dialers through struct fields. Use functional options to customize helper functions and constructors. Constructors take required inputs as ordinary arguments and use option structs for related settings that are shared across entry points, such as WebSocket handshakes and certificate verification. A zero field, omitted option or optional nil argument selects its documented default. For an explicit zero in an option or constructor, follow that parameter's documentation. A negative timeout disables it unless documented otherwise. Other negative values require a documented meaning.

Defaults bound timeouts and limits unless documented otherwise. For example, httpproxy.Server.ResponseHeaderTimeout and socks5.DatagramRelay.IdleTimeout default to no timeout. tlsconn.CertFiles.MaxEntries defaults to no count limit, and CertStore.MaxEntries defaults to DefaultMaxEntries (1024). Both certificate caches default IdleTimeout to DefaultIdleTimeout (24h). forwarded does not import net/http: it takes a header as the map[string][]string that http.Header is.

Install

go get github.com/djylb/netx

Connections

package main

import (
	"context"
	"crypto/tls"
	"log"
	"net"
	"time"

	"github.com/djylb/netx"
	"github.com/djylb/netx/tlsconn"
)

// wrap refreshes an idle deadline before every read and write and counts traffic.
func wrap(c net.Conn) net.Conn {
	c = netx.NewTimeoutConn(c, 30*time.Second)
	return netx.ObserveConn(c,
		func(n int64) error { return nil }, // read
		func(n int64) error { return nil }, // write
	)
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	raw, err := (&net.Dialer{}).DialContext(ctx, "tcp", "example.com:443")
	if err != nil {
		log.Fatal(err)
	}
	// The dial and the handshake are bounded by ctx; on failure raw is closed.
	conn, err := tlsconn.Client(ctx, wrap(raw), &tls.Config{ServerName: "example.com"})
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
}
  • A non-positive idle timeout sets none; SetIdleTimeout changes it later, such as from a short one during a handshake to a longer one after it.
  • TimeoutConn moves the deadline only once less than the idle timeout is left, and then to the idle timeout plus a slack of idle/16 (at most 1s), so the per-call cost is an atomic load. A connection never times out before it has been idle for the idle timeout, and at most that slack later. Idle tracking uses the monotonic clock.
  • Deadlines set with SetDeadline, SetReadDeadline or SetWriteDeadline stay in effect until changed: setting them and each read or write set a direction's deadline to the earlier of that deadline and now plus the idle timeout, so SetReadDeadline(time.Now()) interrupts a blocked Read even while writes continue, and a later or zero deadline does not lift the idle timeout of a Read or Write that is already blocked.
  • tlsconn.Client and tlsconn.Server bound the handshake by the context's deadline, applied as both a connection deadline and through the context, so it also holds on connections that ignore deadlines; a context without a deadline gets DefaultHandshakeTimeout (10s, room for a slow link and a large certificate chain) as a safety bound. They return a *tls.Conn with no deadline set and close the raw connection on failure. They live in their own package so that the root package does not import crypto/tls.
  • tlsconn.Dialer dials with any Forward dialer, such as a proxy dialer, and runs tlsconn.Client on the result, taking the server name from the dialed address unless the config sets one. The context bounds the dial and the handshake; a positive HandshakeTimeout also bounds the handshake, and a negative one leaves the context alone to bound it, without the DefaultHandshakeTimeout fallback. Used as a proxy dialer's Forward, it reaches the proxy over TLS.
TLS certificates

tlsconn also generates self-signed certificates and issues them from a private CA, trusts peers by certificate fingerprint, keeps certificates from files in sync, and picks a certificate for each handshake from many:

// pinnedTunnel serves a self-signed certificate and returns a client config
// that trusts exactly that certificate.
func pinnedTunnel() (server, client *tls.Config, err error) {
	cert, err := tlsconn.NewSelfSigned(tlsconn.SelfSignedOptions{Hosts: []string{"tunnel.internal"}})
	if err != nil {
		return nil, nil, err
	}
	pins := tlsconn.NewPinSet(tlsconn.Fingerprint(cert.Certificate[0]))
	return &tls.Config{Certificates: []tls.Certificate{cert}}, pins.ClientConfig(nil), nil
}

// mutualPins makes each side trust exactly the other's certificate, both
// made with ExtKeyUsage ServerAuth and ClientAuth.
func mutualPins(serverCert, clientCert tls.Certificate) (server, client *tls.Config) {
	clientPins := tlsconn.NewPinSet(tlsconn.Fingerprint(clientCert.Certificate[0]))
	serverPins := tlsconn.NewPinSet(tlsconn.Fingerprint(serverCert.Certificate[0]))
	server = clientPins.ServerConfig(&tls.Config{Certificates: []tls.Certificate{serverCert}})
	client = serverPins.ClientConfig(&tls.Config{Certificates: []tls.Certificate{clientCert}})
	return server, client
}

// reloading serves one certificate from files, picking up a renewal once
// the files change.
func reloading() *tls.Config {
	var certs tlsconn.CertFiles
	return &tls.Config{GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
		return certs.LoadFiles("/etc/certs/fullchain.pem", "/etc/certs/privkey.pem")
	}}
}

// perHost serves certificates from files, picking up renewals as the files
// change.
func perHost() *tls.Config {
	certs := &tlsconn.CertFiles{MaxEntries: 1000, IdleTimeout: 24 * time.Hour}
	return &tls.Config{GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
		dir := filepath.Join("/etc/certs", filepath.Base(hello.ServerName))
		return certs.LoadFiles(filepath.Join(dir, "fullchain.pem"), filepath.Join(dir, "privkey.pem"))
	}}
}
  • NewSelfSigned makes a certificate for DNS names and IP addresses, with a new ECDSA P-256 key or a given one (such as RSA), valid for a year by default and from an hour in the past. It is a server certificate unless ExtKeyUsage says otherwise: x509.ExtKeyUsageClientAuth for a client certificate, or both for peers that take either side. EncodePEM writes it, or any tls.Certificate with an RSA, ECDSA, Ed25519 or ECDH key, as PEM that tls.X509KeyPair reads back. Now and Rand make it by an injected clock and randomness source; validity ends ValidFor after Now.

  • For a private network, NewCA makes a self-signed CA that signs leaves only (MaxPathLen 0), and Issue(ca, opts) signs a leaf for opts.Hosts with opts.ExtKeyUsage (server by default, ClientAuth for mutual TLS), its chain holding the leaf, then the CA, its validity ending no later than the CA's. Peers trust the CA in RootCAs, ClientCAs or CertStore.Roots. It is minimal issuing, not a full CA: there is no revocation.

  • Fingerprint is the SHA-256 of a DER certificate. A PinSet of them, changeable while in use, verifies peers in VerifyConnection, which also runs for resumed sessions, so removing a pin cuts off resumptions too. ClientConfig returns a config that trusts exactly the pinned server certificates; ServerConfig returns one that requires a client certificate (tls.RequireAnyClientCert) and accepts exactly the pinned ones, also in configs that the base's GetConfigForClient returns. Both keep the base config's own VerifyConnection after the pin check. A pin names one exact certificate, so host names and expiry are not checked.

  • CertFiles keeps certificates by file names, or by a hash of PEM data, for GetCertificate callbacks that run on every handshake. Concurrent first loads share one read. Files stay in sync by change: a use at most every CheckInterval (DefaultCheckInterval, 10s; negative never) stats both files, following symbolic links, and reads them again only if the size, modification time or file identity changed, so a certbot-style link swap counts. Once a certificate has expired, its files are read again even when they look unchanged, at most once a minute, and it is not returned (ErrNotValidNow). A read that fails, such as a certificate replaced before its key, or that brings a certificate not valid now while the previous one is (an old pair copied back), keeps the previous certificate, goes to OnError, and is retried at the next check. MaxEntries and IdleTimeout bound the cache without a background goroutine. A zero MaxEntries leaves the entry count unlimited. IdleTimeout uses DefaultIdleTimeout (24h) at zero and keeps entries at negative values. Forget drops one file pair and Clear drops all.

  • CertStore holds certificates by ID and picks one for each handshake, for GetCertificate. File-backed certificates are checked in the background as handshakes arrive. CheckFiles requests an on-demand check. Overlapping calls can return before the refresh finishes. Add, AddPEM and AddFiles take an ID. An empty ID means the certificate file's cleaned path for AddFiles, which stays across renewals, and CertID(cert), the leaf's hex SHA-256 fingerprint, for Add and AddPEM. A fingerprint names one exact certificate, so give certificates that get renewed a stable ID, such as the host configuration's ID or the domain. They serve the leaf's DNS names (wildcards included) and IP addresses, or the names given. Remove, Certificate, List and SetDefault work by ID. One name can match several certificates; a handshake gets:

    1. the one Select names, as a host-routing proxy looks up the requested host's configuration, served even if not for the name; an ID the store does not hold or that is not valid now goes to OnError and the ranking chooses;
    2. else the best for the server name: one the client can use (SupportsCertificate, asked only when there is a choice), then one issued by an authority (verified against Roots, nil for the system roots, when added or read) over a self-signed one, then an exact name over a wildcard (*.example.com, one label), then the later NotAfter, then the one added last;
    3. else the one Load brings for the name;
    4. else the default, which also serves clients without SNI, after any certificate for the IP address they connected to.

    No certificate serves before its NotBefore or from its NotAfter on. Match(name) lists the certificates for a name in this order, each once, with its Role (candidate, loaded or default) and why (authority, wildcard, validity, default, source, files) for an admin view. Load fetches certificates on demand: concurrent handshakes for a name share one call, bounded by LoadTimeout (DefaultLoadTimeout, 30s) even when Load ignores its context, a panic, a failure or a certificate not valid now (expired or not valid yet) fails it, and a failure is remembered for RetryAfter. A loaded certificate is loaded again before it expires (RefreshBefore, or a third of its lifetime if shorter) while it serves on, also when that fails or brings one not valid now; a refresh that finds none stops it serving. Refresh makes one due, also during a load, and Forget drops one; adding a certificate drops what was loaded for the names it covers. Names come from clients, so the loaded ones are bounded by MaxEntries (1024 at 0) and IdleTimeout (24h at 0); have Load turn unknown names away cheaply. Names are matched in ASCII (punycode) form. OnError receives a *CertError (ID, name, files, cause) for every failure no handshake sees, runs without locks held and may call back into the store.

store := &tlsconn.CertStore{
	Select: func(hello *tls.ClientHelloInfo) (string, error) {
		return hosts[hello.ServerName].CertID, nil // "" lets the ranking choose
	},
	Load: func(ctx context.Context, name string) (*tls.Certificate, error) {
		return fetchCertificate(ctx, name) // nil, nil when there is none
	},
	OnError: func(err *tlsconn.CertError) { log.Println(err) },
}
_, err := store.AddFiles("wildcard", "/etc/certs/wildcard/fullchain.pem", "/etc/certs/wildcard/privkey.pem")
store.SetDefault("wildcard")
srv := &http.Server{TLSConfig: &tls.Config{GetCertificate: store.GetCertificate}}
Checking uploaded certificates

For servers that take certificates from users, tlsconn parses and checks them, tells which names they cover, and has the user prove that they hold the private key:

// claim checks an uploaded certificate and key against roots and returns
// the names, of those the user asks for, that it covers. The user must still
// prove possession of the key before getting them.
func claim(certData, keyData []byte, roots *x509.CertPool, domain string, asked []string) (tls.Certificate, []string, error) {
	cert, err := tlsconn.ParseKeyPair(certData, keyData)
	if err != nil {
		return tls.Certificate{}, nil, err // ErrKeyMismatch, ErrEncryptedKey, ...
	}
	chain := []*x509.Certificate{cert.Leaf}
	for _, der := range cert.Certificate[1:] {
		c, err := x509.ParseCertificate(der)
		if err != nil {
			return tls.Certificate{}, nil, err
		}
		chain = append(chain, c)
	}
	// Fails unless the certificate covers domain itself: ErrOnlySubdomains
	// for one that covers only names under it, ErrExpired, ErrSelfSigned, ...
	coverage, err := tlsconn.VerifyDomain(chain, domain, tlsconn.VerifyOptions{Roots: roots})
	if err != nil {
		return tls.Certificate{}, nil, err
	}
	var granted []string
	for _, name := range asked {
		if coverage.Covers(name) { // each name exactly, never the subtree
			granted = append(granted, name)
		}
	}
	return cert, granted, nil
}

// prove has the user sign a challenge with the certificate's key.
func prove(challenger *tlsconn.Challenger, leaf *x509.Certificate, userKey crypto.Signer) error {
	const purpose = "claim example.com for user 42"
	challenge, err := challenger.Challenge(purpose) // sent to the user
	if err != nil {
		return err
	}
	sig, err := tlsconn.SignPossession(userKey, purpose, challenge) // on the user's side
	if err != nil {
		return err
	}
	return challenger.Verify(leaf.PublicKey, purpose, challenge, sig)
}
  • ParseKeyPair takes the chain, leaf first, as PEM (text around the blocks, such as OpenSSL's attributes, and other block types are skipped) or DER, and one private key in PKCS #1, PKCS #8 or SEC 1 form (RSA, ECDSA, Ed25519); both may be in one file. It checks that the key's public key equals the leaf's and returns a tls.Certificate with its Leaf set. ParseCertificates, ParsePrivateKey and MatchKey do the steps alone. Errors are typed: ErrNoCertificates, ErrInvalidCertificate, ErrNoPrivateKey, ErrMultipleKeys, ErrEncryptedKey, ErrInvalidKey, ErrUnsupportedKey and ErrKeyMismatch. Bound the upload's size before parsing.
  • VerifyChain (or VerifyCertificate for a tls.Certificate) verifies the leaf against Roots, with the rest of the uploaded chain, in any order, as intermediates, at Time (zero for now), for KeyUsages (server authentication by default). Uploaded certificates are never trusted as roots. Its errors tell apart ErrExpired, ErrNotYetValid, ErrSelfSigned (which also matches ErrUnknownAuthority), ErrUnknownAuthority, ErrKeyUsage and ErrInvalidChain. IsSelfSigned checks one certificate.
  • Set Roots for uploaded certificates, such as a CA bundle loaded with AppendCertsFromPEM. With nil Roots, Windows, macOS and iOS hand the chain to the platform verifier, which may fetch the issuer URLs (Authority Information Access) named in the certificate, so an uploader could make the server send requests to hosts of their choosing, internal ones included. An explicit pool runs the Go verifier, which fetches nothing. x509.SystemCertPool() does not avoid this: on those systems it holds no certificates and delegates to the platform verifier too.
  • Covers(cert, name) and CertNames(cert) follow RFC 6125 and RFC 9525: only subject alternative names count, never the common name; a DNS name covers itself; *.example.com covers a.example.com, but neither example.com nor a.b.example.com; wildcards must be the whole leftmost label over a base of two labels or more, so *.com, f*.example.com and a.*.example.com cover nothing (and are listed in Names.Invalid); IP addresses match IP address names only. Names are compared by CanonicalName: lowercase, without a trailing dot, international labels as A-labels (bücher.test is xn--bcher-kva.test). Names.Covers answers by binary search; Covers checks a certificate without allocating. For names kept outside a certificate, such as the list a certificate was issued for, CoversName(san, name) applies the same rules to one name in text form (DNS name, wildcard or IP address), and CanonicalSAN gives a DNS name or wildcard in the form Names lists it, or ErrInvalidName for one that covers nothing.
  • VerifyDomain(chain, domain, opts) verifies the chain and requires the certificate to cover the domain itself (Apex, exactly or by a wildcard for its parent, then with ApexByWildcard). One that covers only names under it, such as me.example.net asked about example.net, fails with ErrOnlySubdomains, and one that covers nothing with ErrNotCovered; both come with the coverage, so accepting subdomains is an explicit choice. Names.Under(domain) gives the same DomainCoverage without checks: Apex, exact Subdomains and Wildcards. It is a list of names, never a subtree: a certificate for *.example.com does not cover example.com or a.b.example.com, and one for example.com covers nothing else, so grant each name that DomainCoverage.Covers reports, not the domain's descendants. A self-signed certificate proves nothing about a domain, and fails VerifyDomain unless the roots trust it.
  • A certificate is public, so a user also proves that they hold its key. A Challenger issues challenges bound to a purpose (the action, the user, the domain), each holding its expiry (TTL, 5 minutes by default) and 128 random bits under an HMAC-SHA-256 key of its own, so issuing stores nothing. The user signs with SignPossession: RSA-PSS with SHA-256, ECDSA with SHA-256, SHA-384 or SHA-512 for P-256, P-384 or P-521, or Ed25519, over a message with a fixed context, the purpose and the challenge, so the signature is good for nothing else. Verify checks the challenge, its expiry and the signature against the leaf's public key, and accepts each challenge once: it keeps accepted ones until they expire, at most MaxUsed (65536 by default), and fails closed with ErrTooManyChallenges rather than forget one. Expiry runs on the Challenger's own monotonic clock, so setting the wall clock back cannot revive a used challenge. Make one with NewChallenger; the zero value fails with ErrNoChallenger. A challenge verifies only on the Challenger that issued it and not after a restart; servers behind a load balancer route answers back, or use VerifyPossession with challenges kept in their shared store. Rate-limit proofs per user, since any self-signed key can make one.
  • Summarize describes a certificate for display: subject, issuer, serial number, names, validity, fingerprint, key type and size, and whether it is self-signed or a CA.
Framed messages

FramedConn sends each message as a 2-byte big-endian length followed by up to MaxFramePayload (65535) bytes. Each frame goes out with one write of the connection, header and payload together (a vectored write on TCP), so a layer beneath that compresses or encrypts each write sees whole frames.

func exchange(conn net.Conn, packet []byte) ([]byte, error) {
	framed := netx.NewFramedConn(conn)
	if err := framed.WriteFrame(packet); err != nil {
		return nil, err
	}
	return framed.ReadFrame()
}

// relayDatagrams forwards each frame as one UDP datagram.
func relayDatagrams(tunnel net.Conn, udp *net.UDPConn, peer *net.UDPAddr) error {
	framed := netx.NewFramedConn(tunnel, netx.WithFramedDatagrams())
	buf := make([]byte, netx.MaxFramePayload)
	for {
		n, err := framed.Read(buf)
		if err != nil {
			return err
		}
		if _, err := udp.WriteToUDP(buf[:n], peer); err != nil {
			return err
		}
	}
}
  • By default the connection is a stream: Write sends data longer than MaxFramePayload (65535 bytes) as several frames, and Read returns the current frame, or as much of it as fits in the buffer, waiting for its bytes, and a frame larger than the buffer continues in the following reads, without buffering or allocating. Empty frames carry no stream bytes and are skipped. An error inside a frame returns the bytes read so far, so use WithFramedDatagrams or ReadFrame when message boundaries matter.
  • WithFramedReadBuffer(size) reads the stream through a buffer, so a burst of small frames costs one read of the connection.
  • With WithFramedDatagrams each frame is a message: every Read returns exactly one frame and drops the bytes that do not fit in the buffer, like a UDP socket, an empty frame is returned as a 0-byte read, and Write sends exactly one frame, failing with ErrFrameTooLarge above MaxFramePayload.
  • ReadFrame returns one whole frame, or the rest of a frame that a stream Read has already started.
  • An error that loses no frame bytes is returned unchanged and may be retried: an expired read deadline between frames or inside a frame header, and anywhere in a frame for stream Reads, which keep their place. When frame bytes are lost, by a ReadFrame or datagram Read that fails after part of the payload, the end of the stream inside a frame, or a write that fails partway through a frame, the frame boundaries are lost: that call and every later call in the same direction return an error matching errors.Is(err, netx.ErrFrameDesync), which is never a timeout. The error still matches its cause with errors.Is (an EOF inside a frame becomes io.ErrUnexpectedEOF), except a timeout cause, which is hidden. Close the connection.
Wrapping and unwrapping
func expose(rwc io.ReadWriteCloser, parent net.Conn) net.Conn {
	// Addresses and deadlines come from parent. Closing the result closes rwc
	// and, with WithWrapParentClose, parent too; a parent that rwc already closed is
	// not reported as an error.
	return netx.WrapConn(rwc, parent, netx.WithWrapParentClose())
}

func withAddrs(rawConn net.Conn) net.Conn {
	remote := &net.TCPAddr{IP: net.ParseIP("203.0.113.10"), Port: 443}
	// A nil address falls back to the wrapped connection's own address.
	return netx.NewAddrOverrideConn(rawConn, remote, nil)
}

func socketOf(c net.Conn) net.Conn {
	// Follows the standard NetConn() methods (for example of *tls.Conn and
	// of this package's wrappers) down to the innermost connection.
	return netx.InnermostConn(c)
}

// sniff reads the first bytes of c, within 5s, and hands the connection on
// with those bytes replayed, as if they had not been read. Peek returns after
// the first read, so a client whose first message is short, such as a
// SOCKS5 greeting, does not wait for the timeout; PeekFull reads exactly n.
func sniff(ctx context.Context, c net.Conn) (net.Conn, bool, error) {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	c, first, err := netx.Peek(ctx, c, 5)
	return c, bytes.HasPrefix(first, []byte{0x16, 0x03}), err // a TLS record?
}
  • PrefixConn implements io.WriterTo: after the prefix it copies through the wrapped connection's own WriteTo, so a *net.TCPConn can still splice.
  • The wrappers pass CloseWrite on to the wrapped connection, so a half-close works through them; it returns an error matching errors.ErrUnsupported when the wrapped connection cannot do it.
  • DoWithContext(ctx, c, fn) bounds I/O on c by ctx, and clears c's deadline when fn returns. Like Peek and PeekFull it leaves c open on failure. A cancelable context requires deadline support before ordinary I/O starts. DoHandshake is the same for an exchange that c is no use without: it closes c on failure, after CloseBeneathTLS(c) when the exchange timed out or was canceled, so that a TLS connection sends no close_notify the peer cannot authenticate. Every handshake of this module follows that rule: tlsconn.Client, Server and Dialer, socks5.Dialer.Handshake and Server.Handshake, and proxydial.HTTPDialer.Handshake close the connection they were given when they fail, and return it, or one over it, when they succeed.
Relaying
// forward copies between client and backend until either side stops or ctx
// ends, then closes both.
func forward(ctx context.Context, client, backend net.Conn) {
	up, down, err := netx.Relay(ctx, client, backend)
	log.Printf("sent=%d received=%d err=%v", up, down, err)
}
  • Relay returns the bytes copied in each direction and the error that stopped the relay, or nil at EOF. The failure of a direction is a *netx.RelayError whose From (netx.RelayA or netx.RelayB) names the end whose data was being copied, so each end can be closed with a cause of its own; the end of ctx, the idle timeout and a ConnGroup return their own errors. Errors caused by its own Close calls are not reported.
  • With netx.WithRelayHalfClose(), EOF in one direction is passed on with CloseWrite and the other direction keeps going, for protocols where a client shuts down its sending side and then reads the answer. Ends without CloseWrite are closed as usual. Pair it with an idle timeout.
  • Only a normal end, EOF, reaches the peers as an end of data. Any other stop (an error in either direction, a hook error, the end of ctx, the idle timeout, a ConnGroup) aborts both ends with netx.Abort, so that neither peer takes a cut transfer for a complete one: a *net.TCPConn, also beneath wrappers, is closed with RST (SO_LINGER 0), and an end that implements netx.Aborter (Abort(cause error)), such as a stream of a multiplexed connection or a wsconn connection, is aborted. Wrappers of other packages pass the abort on by implementing Aborter or a NetConn() net.Conn method.
  • The end of ctx ends the relay, aborting both ends, and Relay returns context.Cause(ctx). Cancelling one context ends every relay that shares it, also those idle in a read.
  • WithRelayIdleTimeout(d) ends a relay through which nothing has passed in either direction for d, returning netx.ErrRelayIdle. Relay watches the data it copies, also where it splices, and leaves the ends' deadlines alone, so ends without deadlines work too, and time blocked in a RelayFlow.Wait is not idleness. It keeps the fast paths: splice, in pieces, and the ends' own WriteTo and ReadFrom.
  • WithRelayFlows(aToB, bToA) paces and counts each direction without wrapping the connections. RelayFlow.Wait(ctx, n) runs before each read and returns how many bytes may pass, which a stream reads at most and a datagram ignores, as it is read whole; Done(n) reports the bytes written, so a limiter can charge there and let a later Wait wait out the debt. First(b) gets each direction's first bytes, to tell a connection's protocol or log its start, and End(n, err) is called once when a direction stops, before its end is passed on, with net.ErrClosed for a direction that the relay cut short. An error from Wait or Done ends the relay and is returned. Hooks shared by both directions or by several relays must be safe for concurrent use. A Wait that may block for long must return when its ctx is done: closing a relay's ends does not wake it, so end such relays with their context or WithRelayGroup.
  • netx.Copy(ctx, dst, src, flow), with a nil *RelayFlow for no hooks, copies one direction the same way without closing either end. It returns nil at EOF, and once ctx is done it sets expired deadlines on src and dst to interrupt a blocked read or write and returns context.Cause(ctx).
// forwardMetered relays for one user: limit paces both directions, count
// records what passed, and cancelling ctx ends the user's relays.
func forwardMetered(ctx context.Context, client, backend net.Conn,
	limit func(ctx context.Context, n int64) (int64, error), count func(n int64) error) error {
	flow := netx.RelayFlow{Wait: limit, Done: count}
	_, _, err := netx.Relay(ctx, client, backend, netx.WithRelayFlows(flow, flow))
	return err
}

ExampleWithRelayFlows_limit in the package documentation shows a complete limiter for Wait and Done that many relays can share.

ConnGroup closes connections together, such as all of a user's when its allowance runs out: remove, err := group.Add(conn) adds one (remove is called when it is done; a closed group returns netx.ErrGroupClosed and leaves conn alone), CloseMembers(cause) closes the current members and keeps the group open, and Close also refuses later ones. A connection can be in several groups, and a group in another, whose CloseMembers empties the inner group without closing it. netx.WithRelayGroup(groups...) adds a relay itself, which the groups then end as its context would, waking a blocked Wait; Relay returns netx.ErrRelayGroupClosed, which also matches the cause. group.Track(conn) adds a connection and returns it wrapped so that closing it also removes it, with no remove to call; Relay looks through the wrapper. Hooks such as RelayFlow.Done may call CloseMembers themselves.

Exchanges over connections that carry more afterwards, such as an HTTP request and its response on a kept-alive connection, relay parts of them:

// relayExchange relays a head and a body of n bytes from client to backend,
// and back the response that next returns, leaving both connections open
// for the next exchange when it ends well.
func relayExchange(ctx context.Context, client, backend net.Conn, head []byte, n int64,
	next func() (io.Reader, error), done func() error) error {
	parts := []io.Reader{bytes.NewReader(head), &io.LimitedReader{R: client, N: n}}
	request := &netx.ChainReader{Next: func() (io.Reader, error) {
		if len(parts) == 0 {
			return nil, nil
		}
		p := parts[0]
		parts = parts[1:]
		return p, nil
	}}
	_, _, err := netx.Relay(ctx,
		&netx.RelayEnd{Reader: request, Writer: client, CloseFunc: done},
		&netx.RelayEnd{Reader: &netx.ChainReader{Next: next}, Writer: backend, CloseFunc: done},
		netx.WithRelayHalfClose())
	return err
}
  • RelayEnd{Reader, Writer, CloseWriteFunc, CloseFunc, AbortFunc} is an end made of parts: Relay reads Reader and writes Writer as it would as ends of their own, and calls the functions instead of closing, which leaves the connections open after an exchange that ended well. A relay that stops early aborts its ends to end blocked reads and writes: AbortFunc, or else the connections beneath Reader and Writer are aborted and CloseFunc is called.
  • ChainReader{Next} reads parts one after another, asking for the next one each time a part ends, so that a body can follow a head that tells its length. Relay and Copy copy each part as a source of its own.
  • An *io.LimitedReader over a connection is copied as the connection is, splicing at most N bytes, so a body of known length moves through the kernel while the bytes after it stay unread.
How Relay copies
  • On Linux and Android, a direction between two *net.TCPConns, or between a *net.TCPConn and a *net.UnixConn, is left to the kernel with splice, through a pipe that is held only while data moves, so idle relays hold no pipes. Relay looks through PrefixConn, AddrOverrideConn, TimeoutConn, refreshing its idle deadline itself, and the connections of ConnGroup.Track and NewSingleConnListener, but not through ObserveConn or other wrappers; use RelayFlow to count.
  • Otherwise a direction is copied with the reading end's WriteTo or else the writing end's ReadFrom, as io.Copy would, except those of *net.TCPConn, whose data goes through a pooled 32 KiB buffer instead. On Unix systems a stream read straight from a socket takes that buffer only once the socket is readable, so idle relays hold no buffers either, and a blocked Wait holds none. Such a socket is fed to the writing end's ReadFrom only while it has data: ReadFrom sees a read error once the socket would block, returns, and is called again when the socket is readable, so whatever it takes for a read, such as the send space of a multiplexed stream, is not held while the direction is idle. It must return read errors as io.ReaderFrom does and stay usable after one.
  • A stream source, such as a stream of a multiplexed connection, can implement netx.ReadNotifier: TryRead(p) (int, error), which never blocks and returns netx.ErrWouldBlock, or any error with a method WouldBlock() bool that reports true, while there is nothing to read, and NotifyReadable(f func()) (stop func() bool), which calls f once when the stream becomes readable. Relay then copies from it without a goroutine of its own: a short task copies what there is and ends once the stream would block, and the next notification starts the next one. An idle relay between such a stream and a TCP connection keeps only the goroutine that called Relay, waiting for the TCP side. Copy waits on it before it takes a buffer. See the interface's documentation for its full contract. WrapConn over such a stream returns a connection that is a ReadNotifier too.
  • Sources that return one datagram per read (*net.UDPConn, PacketListener connections, FramedConn with WithFramedDatagrams, and connections of other packages whose local address is on a udp, ip or unixgram network) get one write per datagram, so no datagram is cut short and empty ones are passed on. PacketListener connections hand their queued datagrams over and FramedConns read each frame into a buffer that fits it, so idle UDP relays hold no buffer and each datagram is copied once; other datagram sources get a 64 KiB buffer.
  • A direction with a Wait, Done or First hook still splices, in pieces so that Done sees bytes as they pass, but otherwise goes through Relay's buffer rather than the ends' own WriteTo or ReadFrom.
Dialing the first that connects

DialFirst races attempts that may dial in different ways, such as directly and through a relay or several proxies: it starts them in order, starts the next whenever one fails or has not connected within the stagger (DefaultDialStagger, 300 ms, if 0; only after a failure if negative, as with net.Dialer.FallbackDelay), and closes the connections that losing attempts still make. It returns the index of the attempt that won, or the errors of all attempts, joined.

conn, i, err := netx.DialFirst(ctx, 200*time.Millisecond,
	func(ctx context.Context) (net.Conn, error) { return direct.DialContext(ctx, "tcp", peer) },
	func(ctx context.Context) (net.Conn, error) { return relay.DialContext(ctx, "tcp", peer) },
)

RaceDialer holds the dialers and stagger of such races. Its DialContext races its dialers to one address, so it is itself a netx.ContextDialer and can be an http.Transport's DialContext or a proxy dialer's Forward; its DialAny races the addresses of a service, such as the entry points of a cluster, each through every dialer. The zero RaceDialer dials with a zero net.Dialer and DefaultDialStagger:

d := &netx.RaceDialer{Dialers: []netx.ContextDialer{direct, viaProxy}, Stagger: 200 * time.Millisecond}
transport := &http.Transport{DialContext: d.DialContext}

// addr says which one connected.
conn, addr, err := (&netx.RaceDialer{}).DialAny(ctx, "tcp", "a.example:8024", "b.example:8024")

DialFirst without attempts and DialAny without addresses return netx.ErrNoDialAttempts.

Listeners

// handOff serves connections that were accepted and routed elsewhere.
func handOff(srv *http.Server) *netx.ChanListener {
	l := netx.NewChanListener(&net.TCPAddr{Port: 443}, 128)
	go func() {
		if err := srv.Serve(l); !errors.Is(err, net.ErrClosed) && !errors.Is(err, http.ErrServerClosed) {
			log.Printf("serve: %v", err)
		}
	}()
	return l
}

func route(ctx context.Context, l *netx.ChanListener, c net.Conn) error {
	ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
	defer cancel()
	if err := l.Deliver(ctx, c); err != nil {
		_ = c.Close() // still ours
		return err
	}
	return nil
}

// dialInProcess reaches the same server without a socket.
func dialInProcess(ctx context.Context, l *netx.ChanListener) (net.Conn, error) {
	return l.Dial(ctx, &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 50000})
}

// serveOne runs an http.Server on one connection and returns when the
// connection is closed.
func serveOne(c net.Conn, h http.Handler) error {
	err := (&http.Server{Handler: h}).Serve(netx.NewSingleConnListener(c))
	if errors.Is(err, net.ErrClosed) {
		return nil
	}
	return err
}
  • Deliver waits for queue space until the context is done or the listener closes. On success the listener owns the connection: Accept returns it or Close closes it. On failure the caller keeps it, to close or route elsewhere; TryDeliver queues without waiting.
  • Dial connects through a synchronous net.Pipe. The server end reports the given remote address and the listener address; the client end reports the reverse.
  • NewSingleConnListener returns the connection once. Later Accept calls return net.ErrClosed after the connection or the listener is closed. The connection belongs to the server once accepted: closing the listener then only ends a blocked Accept and leaves the connection being served, so stop an http.Server on it with Shutdown or Close, or close the connection. The accepted connection is a wrapper (unwrap it with InnermostConn), so for TLS wrap the listener with tls.NewListener instead of passing a *tls.Conn.
  • The zero ChanListener is ready, as NewChanListener(nil, 0); the zero SingleConnListener has no connection and its Accept waits for Close.
  • netx.Accept(ctx, l) accepts from any listener, retrying the errors that netx.IsAcceptRetryable reports, such as running out of file descriptors, at once and then with a delay growing from 1ms to 1s; a server loop is for { c, err := netx.Accept(ctx, l); if err != nil { return err }; go serve(c) }.
UDP peers

udpflow.PacketListener splits a packet connection, such as a UDP socket, into one net.Conn per flow, so a UDP server can be written like a TCP server.

func serveUDP(pc net.PacketConn, handle func(net.Conn)) error {
	l := udpflow.NewPacketListener(pc,
		udpflow.WithPacketIdleTimeout(2*time.Minute),
		// Only datagrams that start like the protocol's first message.
		udpflow.WithPacketAcceptFilter(func(peer net.Addr, first []byte) bool {
			return len(first) >= 4 && string(first[:4]) == "HELO"
		}),
	)
	for {
		c, err := l.Accept()
		if err != nil {
			return err
		}
		go handle(c) // each Read is one datagram, each Write sends one
	}
}
  • The first datagram of a new flow starts a connection; later ones are read from it, truncated to the buffer like a UDP socket. Closing a connection lets the next datagram of that flow start a new one.
  • Datagrams are dropped, as a socket buffer would, when a connection's queue (WithPacketQueue, 128) or the accept backlog (WithPacketAcceptBacklog, 128) is full. A datagram larger than 2 KiB takes the room of several, so a queue holds at most 128 × 2 KiB by default however large the datagrams are. WithPacketAcceptFilter sees a new flow's first datagram and can reject it before anything is allocated for the peer; it can answer with l.WriteTo, as a stateless retry does.
  • WithPacketMaxConns(n) caps the connections held at once, accepted or waiting; at the cap a new flow's datagram is dropped before the filter runs or anything is allocated. Spoofed sources can still fill the cap, so pair it with WithPacketIdleTimeout and a filter that checks a token.
  • l.Dial(peer) makes a connection to a known peer from the same socket without Accept, as hole punching needs; it returns udpflow.ErrPacketPeerConnected if the peer has one and udpflow.ErrPacketConnLimit at the cap. With packet information enabled, the first datagram from that peer with a unicast destination at the listener's port fixes the dialed connection's local destination and any link-local scope. Writes before then use the OS-selected source. The binding uses the datagram's claimed source address, so a sender that can spoof the peer's source may bind the connection first.
  • As on a socket, a closed connection or an expired read deadline fails Read even while datagrams are queued.
  • WithPacketIdleTimeout closes a connection that has been idle since Accept returned it; connections still waiting for Accept are not closed, and their datagrams are kept.
  • On a *net.UDPConn the read loop, queueing and writes do not allocate per datagram up to 2 KiB. A connection's queue grows with the datagrams waiting in it, up to its bound, and gives that room back once read, so idle connections hold only a few slots whatever the bound.
  • Lookups of established flows take no lock, and the idle timeout checks only the connections due, so a listener scales from a few peers to millions without a separate mode.
  • WithPacketConns(more...) reads further sockets into the same connections, one read loop each; ListenUDPReusePort(ctx, lc, network, address, n) opens n sockets on one address with SO_REUSEPORT, among which Linux and Android spread peers by source (elsewhere it returns udpflow.ErrReusePortUnsupported for more than one). A connection replies from the socket its flow came through.
  • l.DestinationAware() reports whether every socket enabled packet information at construction. This mode requires wildcard *net.UDPConn sockets (Linux, Android, macOS, iOS and Windows). Unicast flows are keyed by remote address and local destination. Link-local destinations also include the incoming interface in the key. The connection's LocalAddr and reply source use the unicast destination. If that source is temporarily unavailable, the flow retries that datagram with an OS-selected source and tries the fixed source on the next write. If the source is confirmed to be a broadcast or multicast address after a write error, the flow uses OS-selected sources for subsequent writes and LocalAddr reports the socket's address. All broadcast and multicast traffic from a remote address shares one flow with an OS-selected reply source, separate from that address's unicast flows. Datagrams missing packet information are dropped in this mode. If any socket cannot enable packet information, all sockets use remote-only flow keys and OS-selected reply sources. l.WriteTo always uses the OS-selected source. Destination-aware listeners share an IPv4 broadcast-address cache with a system-clock refresh; the last such listener to close stops its worker.
  • WithPacketReadBatch(n) reads up to n datagrams per system call with recvmmsg on Linux and Android, holding n buffers of the WithPacketMaxDatagram size per read loop; elsewhere datagrams are read one at a time.
  • WithPacketRejectCache(size, ttl) with l.RejectPeer(peer) drops a peer's new-connection datagrams before the filter runs, for ttl. Rejections by the filter alone are never remembered, since a source can be spoofed; call RejectPeer only for a source the datagram proves, such as one that echoed a token.
  • The listener owns the socket and closes it, and all connections, on Close. The zero PacketListener has no socket: Accept waits for Close.
  • ListenEphemeralUDP(ctx, lc) opens a UDP socket on a free port for IPv4 and IPv6, as net.ListenUDP("udp", nil) does, except that on macOS and iOS it never takes a port that another socket holds on one IPv4 address, such as 127.0.0.1, which would receive the replies sent there.

Addresses

netx.Addr is a destination as proxy requests name it: an IP address (netip.Addr) or a host name, and a port. socks5 and httpproxy use it for request destinations, so one policy serves both.

dst, _ := netx.ParseAddr("LOCALHOST:443") // {Name: "localhost", Port: 443}
ip, _ := netx.ParseAddr("[::ffff:127.0.0.1]:80") // {IP: 127.0.0.1, Port: 80}
fromName := netx.HostAddr("127.0.0.1.", 80)    // {IP: 127.0.0.1, Port: 80}
  • HostAddr(host, port), ParseAddr, AddrFromAddrPort and AddrFromNetAddr normalise: every IP address goes into IP in one form, IPv4-mapped IPv6 as IPv4 and without a zone, also when it comes as a name that is an IP literal or one with a trailing dot; names are lowercased and never resolved. A policy on IP addresses must therefore also check where names resolve to, in the dialer, since some resolvers read 127.1 or 0x7f.0.0.1 as addresses.
  • String gives host:port for net.Dial, Host the host alone, and the zero Addr prints as 0.0.0.0:0.
Address scopes

ScopeOf classifies an IP address by the IANA IPv4 and IPv6 Special-Purpose Address Registries, and IsGlobal reports whether it is globally reachable unicast:

if !netx.IsGlobal(candidate.Addr()) {
	return // not worth offering to a peer on the Internet
}
switch netx.ScopeOf(addr) {
case netx.ScopePrivate, netx.ScopeShared, netx.ScopeLinkLocal:
	// on the local network or behind carrier-grade NAT
}
  • Scopes: ScopeInvalid, ScopeUnspecified, ScopeLoopback, ScopeLinkLocal, ScopePrivate (RFC 1918, fc00::/7, 64:ff9b:1::/48), ScopeShared (100.64.0.0/10), ScopeMulticast, ScopeBroadcast, ScopeDocumentation, ScopeBenchmarking, ScopeReserved and ScopeGlobal.
  • EmbeddedIPv4 returns the IPv4 address an IPv6 address carries (IPv4-mapped, NAT64 64:ff9b::/96 and 64:ff9b:1::/48, 6to4, IPv4-compatible); ScopeOf uses the same extraction.
  • IPv4-mapped addresses are classified as IPv4; zones are ignored. Globally reachable entries inside reserved blocks, such as the PCP and TURN anycast addresses 192.0.0.9 and 2001:1::1, are global; IPv6 outside 2000::/3 that no entry names is reserved.
  • 6to4 (2002::/16), Teredo (2001::/32) and NAT64 (64:ff9b::/96) addresses are global when the IPv4 addresses they embed are, else reserved.
  • It is a table lookup indexed by the first byte: 2–7 ns for most addresses, no allocation.

Clocks

What times out or expires in the background takes a timeshim.Clock (github.com/djylb/timeshim), so that tests can move time instead of waiting for it. timeshim.Real is the system clock; timeshim.NewFake(t) returns a clock that moves only by Advance, which runs the AfterFunc calls that come due in its own goroutine. A nil Clock means timeshim.Real, so the default behaviour does not change.

  • WithRelayClock, WithPacketClock and transparent.WithFlowClock time the idle timeouts of Relay, PacketListener and FlowListener.
  • socks5.DatagramRelay.Clock times IdleTimeout, and socks5.Server.Clock the idle timeouts of UDP associations.
  • tlsconn.CertStore.Clock, tlsconn.CertFiles.Clock and tlsconn.ChallengerOptions.Clock time file checks, refreshes, certificate validity and challenge expiry.

Socket deadlines and dial and handshake timeouts stay on the system clock.

Error Helpers

func dialStatus(addr string) string {
	c, err := net.DialTimeout("tcp", addr, 5*time.Second)
	switch {
	case err == nil:
		_ = c.Close()
		return "ok"
	case netx.IsConnRefused(err):
		return "refused"
	case netx.IsHostUnreachable(err), netx.IsNetworkUnreachable(err):
		return "unreachable"
	case netx.IsPermissionDenied(err):
		return "blocked"
	case netx.IsTimeout(err):
		return "timeout"
	default:
		return string(netx.NetErrorKind(err))
	}
}

func logReadError(c net.Conn, err error) {
	if netx.IsTimeout(err) {
		return // idle connection
	}
	// kind=conn_reset err="read tcp ...: connection reset by peer" local=... remote=...
	// timeout=false op=read net=tcp source=... addr=... syscall=read errno=...
	// errno_name=ECONNRESET
	log.Printf("read failed: %s", netx.NetErrorDetails(err, c))
}

The classifiers check the platform errno first, so they work whatever the system language is. On Windows this includes the Winsock codes (WSAECONNRESET, WSAETIMEDOUT, ...), which the syscall.E* constants do not match. Errors that only carry text fall back to well-known English messages. Besides the classifiers above there are IsConnReset, IsConnAborted, IsBrokenPipe, IsAddrInUse, IsAddrNotAvailable, IsMessageTooLarge and IsClosed, which reports net.ErrClosed, io.ErrClosedPipe and the "use of closed network connection" text that ends an accept or read loop. NetErrorKind returns an ErrorKind constant named after the classifier that matches (KindConnReset, KindTimeout, ..., KindEOF, KindOther), for metrics. Failed name lookups are KindDNS (IsDNSError, and IsDNSNotFound for names that do not exist), not unreachable, and canceled contexts and operations are KindCanceled (IsCanceled). NetErrorDetails returns that information as fields, for structured logs, and its String formats them as the line above; errno_name/ErrnoName are given only for errnos the classifiers recognise, others appear as the number alone.

Joining halves

duplex.Join(r, w) makes a net.Conn of any reader and writer, such as the response and request bodies of one HTTP exchange, two one-way pipes, or standard input and output, so that code written for connections can use them:

// over runs proto over one streamed HTTP request to a server that answers
// before the request ends: what proto writes is the request body and what
// it reads the response body.
func over(ctx context.Context, url string, proto func(net.Conn) error) error {
	uplink, body := io.Pipe()
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, uplink)
	if err != nil {
		return err
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	c := duplex.Join(resp.Body, body)
	defer c.Close()
	return proto(c)
}
  • CloseRead stops the read half and CloseWrite the write half, with their CloseRead or CloseWrite methods, or else Close; Close closes both. A value that is both halves is closed once, and stays open until both directions are closed when it can only be closed whole. Afterwards reads or writes in that direction return net.ErrClosed.
  • Deadlines go to halves with SetReadDeadline, SetWriteDeadline or SetDeadline. Setting one for a half without them returns an error matching errors.ErrUnsupported; the connection does not emulate them, since a read that cannot be interrupted would need a goroutine that outlives it.
  • Addresses come from the halves that have them, else are duplex. A nil read half reads io.EOF, a nil write half fails writes with errors.ErrUnsupported.
  • Copies to and from standalone sockets and files keep their kernel fast paths. With other peers each read or write is serialized separately. Read and Write do not allocate.

A duplex.Writer is a write half whose stream can be swapped, and a duplex.Reader a read half that reads one stream after another, for a stream that its sender moves from one channel to the next, such as from one upload request to another or to a new connection after a reconnect. The sender swaps; the receiver only appends each channel as it arrives:

// The sender's uplink: writes go to the current upload.
up := new(duplex.Writer)
if err := up.Swap(ctx, firstUpload); err != nil {
	return err
}
c := duplex.Join(downlink, up)

// Later, from the code that rotates uploads: Swap waits for the write in
// progress, holds back the next ones, switches, and closes the first upload,
// which ends its body for the receiver.
if err := up.Swap(ctx, nextUpload); err != nil {
	if replaced, ok := err.(*duplex.ReplacedStreamError); ok {
		// nextUpload belongs to up. Report the previous upload's close error.
		return replaced
	}
	// Installation failed. The caller still owns nextUpload.
	_ = nextUpload.Close()
	return err
}
// The receiver: each upload handler appends its body to the session and
// returns once the session has read it. Reads go on from one body to the
// next in order and wait for the next while there is none.
func (s *session) upload(w http.ResponseWriter, r *http.Request) {
	done, err := s.in.Append(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusGone)
		return
	}
	select {
	case <-done:
	case <-r.Context().Done():
	}
}
  • Every Write goes whole to one stream, and the old stream gets nothing after the swap, so a receiver that reads each channel to its end and then the next reads the bytes in the order they were written. The receiver must append the channels in the order of the swaps; a sender with several goroutines that swap opens each channel and swaps to it under one lock.
  • Swap dials nothing: the sender opens the next channel first, while writes go on into the old one. When its context ends first, Swap leaves both streams as they were.
  • The receiver learns of a swap only from the old stream ending, so each stream must end cleanly when closed, as a request body or a pipe does. A receiver that has not appended the next channel yet loses nothing: the sender's writes wait in that channel's transport and reads wait for the Append, so both sides should bound the wait with deadlines. A sender that must know the old channel was read takes that from its transport, such as the response to the old upload.
  • Reader closes each stream it has read to its end and moves on. While it has none, reads wait for Append, the read deadline or Close; after End they return io.EOF once the streams appended before it are read. An error other than io.EOF is returned and leaves the stream current.
  • Both own their streams: Swap closes the stream it replaces, and Close closes the current one, or the ones left. A Writer without a stream yet holds writes back until the first Swap. Deadlines apply to the waits and to every stream that has deadline methods.
  • Their Read and Write do not allocate, and the plain Conn does not pay for them. A Writer copies through Write, so that a copy into it never holds up a swap; a Reader copies each stream through its own WriteTo or the destination's ReadFrom.

PROXY Protocol

github.com/djylb/netx/proxyproto builds, decodes and serves the PROXY protocol headers that tell a backend the original client and destination of a proxied connection or UDP flow. It depends only on the standard library and not on the netx root package, so importing it adds no more than the header code.

func sendProxyHeader(backend, client net.Conn) error {
	// client.RemoteAddr() is the source, client.LocalAddr() the destination.
	h, err := proxyproto.HeaderFromConn(proxyproto.V2, client)
	if err != nil {
		return err // an address pair the protocol cannot carry
	}
	_, err = h.WriteTo(backend) // one Write
	return err
}

// behindLoadBalancer reports the client addresses sent by trusted balancers
// and passes other peers' connections through untouched.
func behindLoadBalancer(ln net.Listener, balancers ...netip.Prefix) net.Listener {
	return &proxyproto.Listener{Listener: ln, PolicyFor: proxyproto.TrustPrefixes(balancers...)}
}

// sniffed reads the header of a connection accepted and routed elsewhere,
// and finds it again beneath a TLS layer.
func sniffed(raw net.Conn, cfg *tls.Config) (*tls.Conn, *proxyproto.Header, error) {
	tc := tls.Server(proxyproto.NewConn(raw, proxyproto.Config{Policy: proxyproto.Optional}), cfg)
	h, err := proxyproto.HeaderOf(tc) // nil, nil when the peer sent none
	return tc, h, err
}

// udpBehindProxy reads the header from the first datagram of each UDP flow.
func udpBehindProxy(pc net.PacketConn) net.Listener {
	return &proxyproto.Listener{
		Listener: udpflow.NewPacketListener(pc),
		Config:   proxyproto.Config{Datagram: proxyproto.DatagramFirst},
	}
}
  • NewHeader(version, src, dst) builds a header from two addresses, and HeaderFromConn from a connection's; both return an error for a pair the protocol cannot carry, such as a nil source, addresses of other types or a TCP/UDP mix, rather than a header that would attribute the connection to the proxy. Header.WriteTo sends a Header with one Write, and Header.AppendBinary encodes it into a buffer, including version 2 TLVs and AF_UNIX addresses. When a pair cannot be sent, Header{Version: v} sends a header without addresses (v1 PROXY UNKNOWN, v2 AF_UNSPEC, TLVs allowed), and Header{Version: v, Local: true} gives LOCAL for a proxy's own connections.
  • Version 2 TLVs carry an application's own fields in the custom types TLVCustomMin to TLVCustomMax (0xE0–0xEF), such as who a connection belongs to: h.TLVs, err = h.TLVs.Append(proxyproto.TLVCustomMin, id), and h.TLVs.Get reads them back. They are as trustworthy as the peer that sent them, so take them from trusted peers only.
  • h.TLVs.SSL() reads the TLS information a proxy sends (PP2_TYPE_SSL): the client flags, Verified(), and Version, CommonName, Cipher, SigAlg and KeyAlg from its sub-fields; TLVs.AppendSSL sends one.
  • h.TLVs = h.TLVs.AppendCRC32C() adds a CRC32C field, which AppendBinary fills with the header's checksum. Decode and the Conn verify a CRC32C field that a header carries and fail it with ErrChecksum, which matches ErrMalformed, when it does not match.
  • Decode decodes a header at the start of a byte slice and returns it with its length, ErrNoHeader when there is none and io.ErrUnexpectedEOF while it is incomplete, for protocol sniffers.
  • Decoding accepts non-standard senders wherever that cannot misattribute a connection: v1 lines ending in a bare LF, with runs of spaces, any letter case, UDP4/UDP6 tokens, families that differ from the token or padded ports. Binary headers must carry version 2. Unknown commands, protocols and families fall back to the connection's own addresses. A v2 PROXY command in a datagram must declare enough room for its address family.
  • For streams and DatagramFirst, Listener reads the header lazily on the first read or address query, with a timeout (DefaultHeaderTimeout), so a slow peer cannot stall Accept. The read that reaches the timeout returns it. Later reads return a non-timeout error matching ErrNoHeader, so loops that retry timeouts do not spin. Its Config (Policy, HeaderTimeout, Datagram) applies to every accepted connection; Config.Policy is Required (the default), Optional or Ignore, and PolicyFor, when set, picks the policy per peer instead. Only trusted peers should be allowed to send a header: PolicyFor: proxyproto.TrustPrefixes(...) requires one from peers in the given networks and ignores the rest. NewConn does the same for one connection accepted elsewhere, such as a multiplexed stream, and HeaderOf finds the header beneath wrappers with a NetConn method.
  • For streams and DatagramFirst, writes do not wait for the header. Under Required and Optional, a server that speaks first, or one that answers a bad request, writes to a peer that may have sent no header or a malformed one. When that matters, call Header() (or read) first and write only once it succeeds.
  • Set Config.Datagram for connections that return one datagram per read. DatagramFirst reads a header only from the first datagram. If it is absent, Required rejects the flow and Optional passes the entire flow through. Malformed headers and terminal first-read I/O errors fail the flow under either policy. DatagramEach skips datagrams without a header. DatagramAuto passes through datagrams without a complete v1 or v2 signature. Both per-datagram modes skip truncated or malformed headers and count skipped packets in Conn.DroppedDatagrams(). Use Conn.ReadDatagram to get the payload and its header together. These modes use the connection's read deadline, report the transport addresses, and return a nil connection header from Conn.Header and HeaderOf. Ignore always passes traffic through unchanged. Datagram modes convert TCP header addresses to *net.UDPAddr, as Header.UDPAddrs does. Leave Config.Datagram at zero for stream connections.
  • A nil or unspecified target is sent as 0.0.0.0 or ::, matching the client's address family. An IPv4/IPv6 pair is sent as TCP6 (v1) or AF_INET6 (v2), with the IPv4 side in its IPv4-mapped form ::ffff:a.b.c.d. v1 has no UDP token, so UDP pairs are written with TCP4/TCP6; use v2 to mark them as DGRAM.

Transparent Proxying

github.com/djylb/netx/transparent listens for connections that firewall rules redirect to a local port and recovers where they were going. It depends only on the standard library and not on the netx root package.

func serve(ctx context.Context, handle func(c net.Conn, target netip.AddrPort)) error {
	ln, err := transparent.Listen(ctx, "tcp", "0.0.0.0:8080")
	if err != nil {
		return err
	}
	for {
		c, err := ln.Accept()
		if err != nil {
			return err
		}
		dst, redirected, err := transparent.OriginalDestination(c)
		// A connection made to the listener directly would connect the
		// proxy to itself, again and again.
		if err != nil || !redirected {
			_ = c.Close()
			continue
		}
		go handle(c, dst)
	}
}
Platform Listen / Control OriginalDestination
Linux, Android sets IP_TRANSPARENT/IPV6_TRANSPARENT (needs CAP_NET_ADMIN) SO_ORIGINAL_DST (REDIRECT/DNAT), else the local address (TPROXY)
FreeBSD sets IP_BINDANY/IPV6_BINDANY pf DIOCNATLOOK, else the local address
macOS, iOS nothing (pf rdr needs no socket option) pf DIOCNATLOOK (needs root)
Others ErrListenUnsupported ErrOriginalDestinationUnsupported

OriginalDestination also reports whether the connection was redirected. A destination on another port than the connection's local one was redirected. One on the same port was redirected unless it is an address of this host: Linux asks the routing table through the socket's bound device, such as a VRF, and counts IPv6 anycast as local; FreeBSD and macOS bind the address. A direct connection to the listener therefore reports its own address and false, and so do a NAT that maps another address of this host to the listener's own port and TPROXY delivering a connection for an address of this host. A wrapper beneath which no socket can be reached is an error rather than trusting its addresses. Lookup failures, such as a closed connection or no permission to read /dev/pf, are returned as errors. Both unsupported errors match errors.ErrUnsupported. For a plain listener use net.Listen. OriginalDestination follows NetConn methods down to the socket, through wrappers such as *tls.Conn and netx.TimeoutConn, so it can be called on a wrapped connection.

Listen is a net.ListenConfig whose Control is transparent.Control. To combine the transparent options with your own, such as SO_REUSEPORT, SO_MARK or keep-alive settings, call it from your own Control; on a net.Dialer it lets a socket bind an address that is not local:

lc := net.ListenConfig{
	KeepAliveConfig: net.KeepAliveConfig{Enable: true, Idle: 30 * time.Second},
	Control: func(network, address string, c syscall.RawConn) error {
		if err := transparent.Control(network, address, c); err != nil {
			return err
		}
		return setReusePort(c) // your own options
	},
}
ln, err := lc.Listen(ctx, "tcp", "0.0.0.0:8080")

transparent.ControlPacket does the same for UDP and also asks for each datagram's original destination.

On Linux and Android, ListenPacket, ReadFromUDP and DialUDP handle UDP redirected by TPROXY. ListenPacket is a net.ListenConfig with transparent.ControlPacket as its Control. ReadFromUDP returns, with the datagram's length, a PacketInfo: its source Src, its original destination Dst, and Redirected, false for a datagram sent straight to the listener, which must not be relayed back to it. DialUDP opens a socket bound to Dst to answer from it.

A datagram for another port, or for another address when the listener is bound to one, was redirected. On a wildcard listener's own port the destination is looked up as for TCP; addresses found local are remembered for a minute. Listening on a port that redirected traffic does not use avoids the lookup, and DialUDP needs it anyway.

func serveRedirectedUDP(ctx context.Context) error {
	ln, err := transparent.ListenPacket(ctx, "udp", "0.0.0.0:8080")
	if err != nil {
		return err
	}
	buf := make([]byte, 65535)
	for {
		n, info, err := transparent.ReadFromUDP(ln, buf)
		if errors.Is(err, transparent.ErrControlTruncated) {
			continue // this datagram's destination is unknown
		}
		if err != nil {
			return err
		}
		if !info.Redirected {
			continue // sent to the listener itself
		}
		reply, err := transparent.DialUDP(ctx, info.Dst, info.Src)
		if err != nil {
			continue
		}
		_, _ = reply.Write(buf[:n])
		_ = reply.Close()
	}
}

ListenUDPFlows does the flow keeping instead: its FlowListener accepts one *FlowConn per source and original destination. Each Read returns one of the flow's datagrams, and Write answers the source from the original destination through a DialUDP socket that the first Write opens and Close closes; the source's later datagrams arrive on that socket and are read from the flow like the first. RemoteAddr is the source and LocalAddr the original destination. Datagrams sent straight to the listener are dropped unless WithFlowDirect is given; FlowConn.Redirected then tells them apart, and they are answered from the listener. WithFlowIdleTimeout, WithFlowQueue, WithFlowAcceptBacklog and WithFlowMaxConns bound idle flows, queued datagrams, flows waiting for Accept and flows held at once, as the WithPacket options of udpflow.PacketListener do; set an idle timeout and a cap for traffic from untrusted sources. As on a socket, an expired read deadline fails Read even while datagrams are queued. netx.Relay and netx.Copy take a flow's queued datagrams whole, copying each once. NewFlowListener builds one on a socket of your own set up with ControlPacket.

func forwardUDPFlows(ctx context.Context) error {
	l, err := transparent.ListenUDPFlows(ctx, "udp", "0.0.0.0:8080",
		transparent.WithFlowIdleTimeout(time.Minute))
	if err != nil {
		return err
	}
	defer func() { _ = l.Close() }()
	for {
		c, err := l.Accept()
		if err != nil {
			return err
		}
		go func() {
			var d net.Dialer
			upstream, err := d.DialContext(ctx, "udp", c.LocalAddr().String())
			if err != nil {
				_ = c.Close()
				return
			}
			_, _, _ = netx.Relay(ctx, c, upstream)
		}()
	}
}

For TCP keepalive tuning, use the standard library:

func keepAlive(c *net.TCPConn) error {
	return c.SetKeepAliveConfig(net.KeepAliveConfig{
		Enable:   true,
		Idle:     30 * time.Second,
		Interval: 10 * time.Second,
		Count:    3,
	})
}

SOCKS5

github.com/djylb/netx/socks5 reads and writes SOCKS5 messages (RFC 1928), username/password authentication (RFC 1929) and SOCKS4/SOCKS4a messages for clients and servers, and provides a client Dialer and a Server built on them. The codec functions neither dial nor listen, and every message is written with a single Write.

// handshake runs the server side of a SOCKS5 CONNECT without authentication.
func handshake(c net.Conn) (netx.Addr, error) {
	methods, err := socks5.ReadMethods(c)
	if err != nil {
		return netx.Addr{}, err
	}
	if !slices.Contains(methods, socks5.MethodNoAuth) {
		_ = socks5.WriteMethod(c, socks5.MethodNoAcceptable)
		return netx.Addr{}, socks5.ErrNoAcceptableMethod
	}
	if err := socks5.WriteMethod(c, socks5.MethodNoAuth); err != nil {
		return netx.Addr{}, err
	}
	cmd, dst, err := socks5.ReadRequest(c)
	switch {
	case errors.Is(err, socks5.ErrAddrType):
		_ = socks5.WriteReply(c, socks5.ReplyAddrTypeNotSupported, netx.Addr{})
		return netx.Addr{}, err
	case err != nil:
		return netx.Addr{}, err
	case cmd != socks5.CmdConnect:
		_ = socks5.WriteReply(c, socks5.ReplyCommandNotSupported, netx.Addr{})
		return netx.Addr{}, fmt.Errorf("unsupported %v", cmd)
	}
	return dst, nil // dial dst, then socks5.WriteReply(c, socks5.ReplySucceeded, bound)
}

// udpRelay unwraps a UDP ASSOCIATE datagram and wraps the answer.
func udpRelay(packet []byte, exchange func(dst string, payload []byte) (net.Addr, []byte)) ([]byte, error) {
	dst, n, err := socks5.DecodeDatagram(packet)
	if err != nil {
		return nil, err
	}
	from, answer := exchange(dst.String(), packet[n:])
	return socks5.AppendDatagram(nil, netx.AddrFromNetAddr(from), answer)
}
  • Addresses are netx.Addr values, an IP address (netip.Addr) or a domain name, and a port (see Addresses). AppendAddr encodes one: IPv4-mapped addresses are sent as IPv4, zones are dropped, and the zero Addr is sent as 0.0.0.0:0.
  • ReadReply returns a *socks5.ReplyError for a reply other than ReplySucceeded. DecodeAddr decodes an address embedded in another message. DecodeDatagram returns the address and the header length (the payload is packet[n:]), rejects fragments with ErrFragmented and ignores the reserved field.
  • ReadRequest4, WriteRequest4, WriteReply4 and ReadReply4 handle SOCKS4, and SOCKS4a for domain names. SOCKS4 replies (Reply4Granted, Reply4Rejected, ...) share the Reply type, whose SOCKS5 codes they do not overlap, so ReadReply4 also fails with a *socks5.ReplyError.
Client

socks5.Dialer dials TCP through a SOCKS5 proxy with CONNECT, or a SOCKS4 or SOCKS4a proxy with SOCKS4 set. Host names are sent to the proxy, which resolves them, unless Resolver resolves them first, as SOCKS4 servers without the 4a extension need. A non-success reply is returned as a *socks5.ReplyError.

func dialSOCKS(ctx context.Context, target string) (net.Conn, error) {
	d := &socks5.Dialer{
		ProxyAddr: "127.0.0.1:1080",
		Username:  "alice", // also offers no authentication
		Password:  "secret",
		Forward:   &net.Dialer{Timeout: 10 * time.Second},
	}
	ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
	defer cancel()
	return d.DialContext(ctx, "tcp", target)
}

For SOCKS over TLS, give the dialer a Forward that returns TLS connections: &tls.Dialer{Config: cfg} or, to reach the proxy through another dialer, &tlsconn.Dialer{Config: cfg, Forward: next}.

Handshake(ctx, conn, cmd, dst) runs the client handshake on a connection you already have and returns the bound address of the reply; DialContext is Forward plus Handshake. On failure it closes the connection, as netx.DoHandshake does, which netx.CloseBeneathTLS helps for exchanges of your own.

ListenPacket opens a UDP association (SOCKS5 only). The returned *socks5.UDPConn sends with WriteTo(payload, dst) and receives with ReadFrom, accepting datagrams only from the proxy's relay. Closing it ends the association, and the proxy closing the control connection closes it. AsNetPacketConn adapts it to net.PacketConn for code that sends to and receives from net.Addr (*net.UDPAddr for IP sources, a netx.Addr for names). Because it is a socks5.PacketConn, a Server can relay UDP through another proxy:

s := &socks5.Server{
	UDPSocket:  udp,
	DialPacket: func(ctx context.Context, _ *socks5.Request) (socks5.PacketConn, error) {
		return upstream.ListenPacket(ctx)
	},
}
Server

socks5.Server serves SOCKS5 CONNECT and UDP ASSOCIATE, and SOCKS4/SOCKS4a CONNECT when SOCKS4 is set. Every field is optional; the zero Server accepts anonymous clients and dials directly.

func runSOCKS(ln net.Listener, udp net.PacketConn) error {
	s := &socks5.Server{
		Auth: []socks5.Authenticator{
			socks5.Credentials(map[string]string{"alice": "secret"}),
		},
		Allow: func(ctx context.Context, req *socks5.Request) error {
			if req.Dst.Port == 25 {
				return &socks5.ReplyError{Reply: socks5.ReplyNotAllowed}
			}
			return nil
		},
		UDPSocket: udp, // one fixed UDP port for every association
	}
	return s.Serve(ln)
}
  • Hooks: Auth (any Authenticator), Allow, Dial (its error picks the reply code through ReplyFor, and the target's LocalAddr is the bound address of the reply: wrap the target in netx.NewAddrOverrideConn to report another), RelayOptions (netx.RelayOptions for the netx.Relay between req.Conn and the target, such as WithRelayFlows per req.User, WithRelayGroup or WithRelayIdleTimeout; the relay always half-closes, so a client that shuts down its sending side still gets the reply, and a half-closed connection then lasts until the other side finishes or closes too, unless an idle timeout ends it), Handle (serves commands of its own, such as BIND, or takes over CONNECT, inside Serve, see below), and for UDP DialPacket (the outbound side, a socks5.PacketConn that receives domain names unresolved, for example to forward through a tunnel), AllowPacket and UDPAddr (the address advertised to clients).
  • Allow and AllowPacket see every IP address a client sends in Dst.IP, including IPv4-mapped IPv6 addresses and domain names that are IP literals, also with one trailing dot such as 127.0.0.1.. Other names arrive unresolved, so an IP policy must also check the resolved address where Dial or DialPacket resolves it, for example with a net.Dialer Control function: some resolvers accept forms such as 127.1. The unspecified addresses 0.0.0.0 and :: reach the server's own host on many systems.
  • UDP on a fixed port (UDPSocket): datagrams must come from the IP address of their association's control connection, so a client cannot claim the datagrams of others. Among the associations of that IP waiting for their first datagram, a source goes to the one that announced its port, else to the only one that announced no port, else to the only one; ambiguous sources are dropped. An announced port counts at the control connection's IP whatever address comes with it, as clients behind a NAT announce their private address and clients that do not know theirs announce 0.0.0.0 or a name; a client that announces the control connection's own address and a port gets datagrams from that exact source alone. A control connection without an IP address, such as a tunneled stream, must announce the client's IP address, or the request is refused; nothing proves that announcement, so such a client can claim the datagrams of any IP address, and only trusted clients may reach UDPSocket that way. ListenUDP instead gives each association its own socket, which without a known client IP takes the first source that sends; use it for untrusted tunneled clients. socks5.ListenAssociationUDP is such a ListenUDP, on the address the client reached the server at. Replies from any source are relayed (full cone), and a reply that cannot be delivered is reported to OnError and dropped. Datagrams to names do not hold up the others while the names are looked up (see NewPacketConn). An association ends with its control connection, or after UDPIdleTimeout, which closes the control connection; UDPOutlivesControl keeps it for clients that close the control connection early.
  • OnError receives the errors that end connections and drop datagrams, for logging; the package itself does not log. A refused request is reported as a *socks5.ReplyError holding both the reply sent and its cause in Err (socks5: connection not allowed by ruleset: no mail).
  • UserPassAuth.Check(ctx, conn, user, password) (ok, err) sees the connection for per-address rules; an error, such as an unreachable account backend, rejects the client and is returned instead of ErrAuthFailed. Credentials builds a UserPassAuth for a fixed account map, comparing SHA-256 digests in constant time so that timing reveals neither password lengths nor which users exist.
  • Custom commands: set Handle, which runs after Allow and before the built-in commands; returning handled true, or having replied at all, means it served the request with req.Reply and req.Conn, and the connection still counts for Shutdown and ActiveConns. To drive the steps yourself, Handshake(ctx, conn) runs the negotiation, authentication and request read, also for SOCKS4, and returns the *socks5.Request without replying, or closes conn when it fails. Answer it with req.Reply(code, bound), which writes SOCKS4 or SOCKS5 as the client spoke, once, or twice for BIND (the listening address, then the peer's; a failure reply is the last), and use req.Conn, which includes any bytes the client sent right after a SOCKS4 request. Or hand it to ServeRequest, which runs Allow, serves CONNECT and UDP ASSOCIATE, and answers other commands with ReplyCommandNotSupported. ServeConn(ctx, conn) is the two in sequence, and ends the connection when ctx ends; Serve passes a context that Close cancels. Request.User is the authenticated identity; Request.UserID4 is the unauthenticated SOCKS4 user ID.
  • ListenAndServe(addr) listens on a TCP address (:1080 when empty) and runs Serve, which retries temporary Accept errors as netx.Accept does.
  • Shutdown(ctx) closes the listeners and waits for the connections being served, including UDP control connections, then calls Close; when ctx ends first, Close ends the rest. ActiveConns reports how many connections Serve and ServeConn are serving.
  • The server runs over any net.Conn. For SOCKS over TLS, serve tls.NewListener(ln, cfg): the TLS handshake happens within HandshakeTimeout. UDP ASSOCIATE then has a TLS control connection, and its datagrams stay plain UDP. To share a port with HTTP or TLS, sniff the first byte (5 for SOCKS5, 4 for SOCKS4, 0x16 for a TLS handshake) and pass SOCKS connections to ServeConn(ctx, conn), after tlsconn.Server for TLS ones.
  • For non-standard clients, a server without required authentication accepts an empty or mismatched method list (username/password with any credentials), and reserved bytes and the username/password version byte are not checked. A custom MethodNoAuth authenticator, such as an IP allowlist, still decides on those clients and on SOCKS4 ones.
UDP relay

socks5.DatagramRelay relays UDP ASSOCIATE datagrams (RFC 1928 section 7 headers) between a stream that carries them one per message, such as a netx.FramedConn made with netx.WithFramedDatagrams over a tunnel, and a socks5.PacketConn that sends them on. It is the UDP half of a server whose clients reach it through such a stream, for example the egress end of a tunnel:

func serveUDPTunnel(ctx context.Context, tunnel net.Conn) error {
	udp, err := netx.ListenEphemeralUDP(ctx, nil)
	if err != nil {
		_ = tunnel.Close()
		return err
	}
	r := &socks5.DatagramRelay{
		Allow:       func(dst netx.Addr) bool { return dst.Port != 25 },
		IdleTimeout: 3 * time.Minute,
	}
	framed := netx.NewFramedConn(tunnel, netx.WithFramedDatagrams(), netx.WithFramedReadBuffer(16<<10))
	return r.Relay(ctx, framed, socks5.NewPacketConn(udp))
}
  • Each datagram read from the stream is decoded and its payload sent to its destination; each reply is written back with one Write, headed by its source. With a NewPacketConn egress, one socket sends everything, so the relay behaves as a full-cone NAT: every destination sees the same source address and port, and replies from any address and port are delivered, including from peers that were never sent to.
  • Datagrams with a fragment number other than 0 are dropped (fragmentation is not supported), as are truncated ones and ones longer than any UDP datagram (ErrDatagramTooLarge); OnError receives the reason. A failed send, or a reply the stream does not take, is reported and dropped without ending the relay.
  • Hooks: Allow (drop by destination; names arrive unresolved), Sent and Received (destination or source and payload length, for counting), OnError and IdleTimeout (ends with netx.ErrRelayIdle).
  • Relay returns when ctx ends (context.Cause(ctx)), when the stream reaches EOF or either side is closed (nil), on an error of either side, or when idle, and it closes both sides. Each direction reuses one buffer; datagrams to IP addresses are relayed without copying or allocating.
  • socks5.Server serves its UDP associations with the same relay.

NewPacketConn resolves names without blocking WriteTo: a datagram to a name that is not cached is held while the name is looked up and then sent, in order with the later datagrams to that name, while datagrams to other destinations pass meanwhile. Results are cached for a minute and failures for five seconds, which WriteTo then reports. Up to 64 names are looked up at once, each holding up to 16 datagrams and 256 KiB in all; datagrams beyond that are dropped with ErrLookupBusy, as a full socket buffer would drop them. Replies always carry the IP address they came from.

HTTP Proxy

github.com/djylb/netx/httpproxy is an HTTP/1.x proxy server. It serves CONNECT with a tunnel, and forwards requests for absolute http URIs (GET http://example.com/ HTTP/1.1), streaming bodies both ways, with several requests per client connection, also to different hosts, over connections to targets that it keeps for later requests. On Linux, tunnels and bodies of a known length are spliced. It parses HTTP with httphead rather than net/http, which would add about 1.7 MB and crypto/tls to a program (linux/amd64, stripped).

func runHTTPProxy(ln net.Listener) error {
	s := &httpproxy.Server{
		Auth: []httpproxy.Authenticator{
			httpproxy.Credentials(map[string]string{"alice": "secret"}),
		},
		Allow: func(ctx context.Context, req *httpproxy.Request) error {
			if req.Dst.Port == 25 {
				return &httpproxy.StatusError{Code: 403}
			}
			return nil
		},
		RelayOptions: func(*httpproxy.Request) []netx.RelayOption {
			return []netx.RelayOption{netx.WithRelayIdleTimeout(5 * time.Minute)}
		},
	}
	return s.Serve(ln)
}
  • Server has the shape of socks5.Server, so that one policy serves both on one port: the hooks Auth, Allow, Handle, Dial, RelayOptions and OnError have the same signatures over *httpproxy.Request, whose Dst is a netx.Addr, User the authenticated identity and Conn the client connection. BasicAuth.Check has the signature of socks5.UserPassAuth.Check, so one function, such as socks5.Credentials(accounts).Check, checks the clients of both. StatusError{Code, Err} and StatusFor(err) are the counterparts of socks5.ReplyError and ReplyFor: a dial timeout is 504, a refused or unreachable target 502, and an Allow error 403 unless it carries another code.
  • Auth lists authenticators by scheme; requests without credentials get 407 with a Proxy-Authenticate challenge for each, on a connection that stays open for the retry, unless the list holds a NoAuth authenticator, which then decides on them. Every request is authenticated: a later request of a kept-alive connection without the credentials is refused, and only credentials identical to ones that passed are not checked again. Only Basic is built in; Digest and other per-request schemes can be added as an Authenticator, while connection-based ones such as NTLM are not supported.
  • RelayOptions applies to the netx.Relay of every tunnel and of every forwarded request, whose relay carries the request to the target and the responses back, so WithRelayFlows paces and counts both exactly, per req.User, also where bodies are spliced, and WithRelayIdleTimeout bounds stalled bodies and the wait for a response. OnDone(req, Result) reports each request's status, bytes each way, whether its target connection was reused, and its error, for access logs.
  • Connections to targets are kept per reuse key, Dst and User by default: a Dial that depends on more, such as a field, needs a ReuseKey, which can also return false to keep none for a request. MaxIdleConnsPerKey (16), MaxIdleConns (1024) and IdleConnTimeout (90 s) bound them; DisableKeepAlives keeps none. A kept connection that the target closes, or that sends anything unasked, leaves the pool at once, and a request that finds one dead before any response is sent again on a new one only when it is idempotent and has no body; nothing else is ever sent twice. A response with Connection: close, or read until close, ends its target connection. Shutdown and Close close the kept connections.
  • Forwarding follows RFC 9110 and 9112: the fields of one connection (Connection and those it lists, Keep-Alive, Proxy-Connection, Proxy-Authorization, TE, Upgrade) are removed, Host comes from the URI, requests go out as HTTP/1.1, and the server writes the framing itself, Content-Length or chunked, with the chunks of a chunked body decoded strictly and encoded again, so that the target reads the body the way the server did; trailers are passed on without fields that framing or routing depend on. Via adds the proxy to Via, and ForwardHeader and ResponseHeader can add fields such as X-Forwarded-For or Forwarded; fields that could inject a line are refused. Interim responses such as 100 Continue are passed on to HTTP/1.1 clients; HTTP/1.0 clients, also with Connection: keep-alive, get chunked responses without chunking and responses read until close are re-chunked for HTTP/1.1 clients; transfer codings before chunked in a response, such as gzip, chunked, are passed on. HEAD, 1xx, 204 and 304 responses have no body. Upgrade requests, such as WebSocket, become a relay once the target switches protocols. TRACE and OPTIONS with Max-Forwards: 0 are answered by the proxy, which counts other values down, and OPTIONS * is answered too.
  • Intercept forwards requests for a path, as clients send to the origin, for connections redirected to the proxy: httpproxy.HostDst takes the destination from Host, and a hook of your own can use the original destination of a redirected connection.
  • Requests that could be read in two ways are refused and end the connection: Content-Length with Transfer-Encoding, differing lengths, transfer codings other than chunked, Transfer-Encoding in HTTP/1.0, obsolete line folding, whitespace before a colon, control characters in fields, two Host fields and user information in the URI. After a reply that ends a connection while the client may still be sending, the server reads on for up to 500 ms or 256 KiB, so that the reply is not lost to a reset. Heads are bounded by MaxHeaderBytes (64 KiB), reading them by HandshakeTimeout, idle kept-alive connections by IdleTimeout, and the wait for a response head, if set, by ResponseHeaderTimeout (504).
  • For non-standard clients, CONNECT is also taken in lower case, without a Host field and without a port (443), lines may end in LF alone, and empty lines before a request are skipped.
  • The zero Server is an open proxy, as the zero socks5.Server is: serve it only to trusted clients, or set Auth and Allow; as there, Allow sees names unresolved, so check resolved addresses in Dial. CONNECT reaches any port that Allow lets through.
  • Dial can reach targets through another proxy, such as a proxydial.HTTPDialer or socks5.Dialer, which chains them.
  • ServeConn(ctx, conn) serves any net.Conn, such as a TLS connection or a netx.PrefixConn from netx.Peek, so one port can serve SOCKS, HTTP proxy requests and both over TLS:
func serveMixed(ctx context.Context, c net.Conn, socks *socks5.Server, web *httpproxy.Server, cfg *tls.Config) {
	c, first, err := netx.Peek(ctx, c, 1)
	if err != nil || len(first) == 0 {
		_ = c.Close()
		return
	}
	switch first[0] {
	case socks5.Version5, socks5.Version4:
		_ = socks.ServeConn(ctx, c)
	case 0x16: // TLS: an https proxy or SOCKS over TLS
		if tc, err := tlsconn.Server(ctx, c, cfg); err == nil {
			serveMixed(ctx, tc, socks, web, nil)
		}
	default:
		_ = web.ServeConn(ctx, c)
	}
}
HTTP heads

github.com/djylb/netx/httphead reads and parses HTTP/1.x heads on its own, for sniffers and servers, with the standard library alone:

head, err := httphead.Read(br, nil, 64<<10) // up to the empty line; the body stays in br
req, err := httphead.ParseRequest(string(head), nil)
target, err := httphead.ParseTarget(req.Method, req.Target)
framing, n, err := httphead.RequestBody(req.Header, req.Minor)
  • Read reads a head into a reused buffer, also with lines longer than the reader's buffer, skipping empty lines before it; ParseRequest, ParseResponse and ParseHeader split it into one string's substrings, keeping the fields' order and names. They refuse what two readers could read differently: CR inside a line, obsolete line folding, whitespace before a colon, names that are not tokens and control characters in values (ErrMalformed); versions other than 1.x give ErrVersion.
  • RequestBody and ResponseBody tell how a body is delimited, refusing Content-Length with Transfer-Encoding in requests and differing lengths, and ParseChunkSize reads chunk-size lines; ParseTarget splits a request-target in any of its four forms.
  • Header has Get, Values, Count, Has, HasToken, Add, Set and Del, and AppendTo writes it back, refusing fields that would add a line.

Real client addresses

forwarded.Resolver finds the client of a request behind trusted proxies. It starts at the TCP peer and, while the hop it is at is trusted, steps to the address that hop recorded, from the right, so that addresses a client prepends are never read:

trusted, err := forwarded.ParsePrefixSet("10.0.0.0/8", "fd00::/8")
r := &forwarded.Resolver{Trusted: trusted} // X-Forwarded-For

func handler(w http.ResponseWriter, req *http.Request) {
	peer, _ := forwarded.ParseNode(req.RemoteAddr)
	c := r.Resolve(peer, req.Header)
	log.Println(c.Addr.Addr())
}
  • Header picks the one field the proxies set: HeaderXForwardedFor (all field lines, comma lists), HeaderForwarded (RFC 7239: quoted values, IPv6 in brackets, ports, obfuscated identifiers and unknown) or HeaderXRealIP; Name reads another field with the same syntax, such as Cf-Connecting-Ip. Fields of the other kinds are ignored, as a client may have sent them.
  • Client holds the address (IPv4 for IPv4-mapped, port 0 when none was recorded), the number of trusted hops, and Opaque when a trusted proxy recorded an obfuscated or unparsable hop, in which case the address is that proxy's.
  • Resolver.Metadata defaults to zero and leaves Client.Proto and Client.Host empty. Enable each field with forwarded.TrustProto or forwarded.TrustHost. With HeaderForwarded, the scheme and host come from the same element as the resolved client address. A missing or opaque address in the selected element leaves both fields empty.
  • With HeaderXForwardedFor or HeaderXRealIP, including a custom Name, enable a field when the trusted TCP peer removes client-supplied values or writes its own as the last value of X-Forwarded-Proto or X-Forwarded-Host. Use Metadata: forwarded.TrustProto when the proxy sets the scheme and the application needs it. These fields describe the request as received by the nearest trusted proxy and can differ from what the client used at the first proxy. An enabled field is read independently of whether the address header named a client.
  • Forwarded is parsed from the right as well, so that elements a trusted proxy appends are read even after a malformed or hostile one.
  • PrefixSet.Prefixes() returns the smallest covering prefixes in address order. Len() counts valid input prefixes, including duplicates.
  • PrefixSet is built once, merges overlapping prefixes and looks addresses up by binary search over disjoint address ranges. Resolve does not allocate: 15 ns for an untrusted peer, 80–250 ns through one or more proxies.
  • AppendXForwardedFor, AppendForwarded and AppendElement format the fields a proxy passes on.

Header rewriting

httprewrite compiles templates with variables in the style of common reverse proxies once and expands them per request, and applies rules that set, add or delete fields:

rules, err := httprewrite.ParseRules(`
X-Forwarded-For: ${proxy_add_x_forwarded_for}
X-Forwarded-Proto: ${forwarded_proto}
X-Real-IP: ${remote_addr}
X-Internal-Token: ${unset}
`, nil)
rw := &httprewrite.Rewriter{
	Request:   rules,
	Redirects: []httprewrite.Redirect{{To: httprewrite.MustCompile("${forwarded_proto}://${http_host}", nil)}},
	Resolver:  &forwarded.Resolver{Trusted: trusted, Metadata: forwarded.TrustProto},
}
proxy := &httputil.ReverseProxy{
	Rewrite: func(pr *httputil.ProxyRequest) {
		pr.SetURL(backend)
		if err := rw.Rewrite(pr); err != nil {
			log.Print(err)
		}
	},
	ModifyResponse: rw.ModifyResponse,
}
  • Built-in variables cover the scheme, host, method, request URI, path, query, client and TCP peer addresses, local address, forwarding fields with this hop appended, the families http_NAME, upstream_http_NAME, cookie_NAME and arg_NAME, the response status and the time. Vars add the program's own, reading Context.Data. Unknown variables are compile errors; $$ is a literal $.
  • An expansion that would put a control character such as CR, LF or NUL in a field value fails, so that no variable, such as the decoded path, can inject a field. Values are used as written, without HTML unescaping.
  • A rule whose value expands to nothing deletes the field, so that Upgrade: ${http_upgrade} sends none for ordinary requests; ${unset} deletes it always. Rules on Host set the request's Host.
  • Redirects rewrite Location and the URL of Refresh; an empty From matches the backend's own origin.
  • Use ReverseProxy's Rewrite, not Director: hop-by-hop fields are removed after Director, so rules on them would be lost. In Rewrite, variables read the inbound request, which still holds Connection, Upgrade and the client's forwarding fields.
  • Expanding into a buffer does not allocate; a template that is a literal or a single field such as ${http_host} expands to a string without allocating.

WebSocket

github.com/djylb/netx/wsconn implements WebSocket (RFC 6455) for tunnels, proxies and message channels: the opening handshake on both sides, a message API, and StreamConn, a net.Conn that carries a byte stream over binary messages. permessage-deflate (RFC 7692) is optional. It reads handshakes with httphead and links neither net/http nor crypto/tls; wsconn/wshttp upgrades the requests of a net/http handler, also over HTTP/2.

// serveTunnel accepts WebSocket tunnels on raw connections, such as those
// a port multiplexer hands over, and relays each to a backend.
func serveTunnel(ctx context.Context, raw net.Conn, backend string) {
	c, err := wsconn.Accept(ctx, raw, &wsconn.ServerOptions{CheckOrigin: wsconn.AnyOrigin})
	if err != nil {
		return // answered with 4xx and closed
	}
	tunnel := wsconn.NewStreamConn(c) // RemoteAddr keeps the port
	dst, err := net.Dial("tcp", backend)
	if err != nil {
		_ = c.CloseWithStatus(wsconn.StatusTryAgainLater, "backend down")
		return
	}
	_, _, _ = netx.Relay(ctx, tunnel, dst)
}

// dialTunnel reaches a wss URL through a TLS dialer that verifies the
// server, over an upstream proxy if forward is one.
func dialTunnel(ctx context.Context, url string, forward netx.ContextDialer) (net.Conn, error) {
	d := &wsconn.Dialer{
		ClientOptions: wsconn.ClientOptions{Host: "tunnel.example.com"},
		Forward:       forward,
		TLS:           &tlsconn.Dialer{Forward: forward, Config: &tls.Config{}},
	}
	c, _, err := d.Dial(ctx, url)
	if err != nil {
		return nil, err
	}
	return wsconn.NewStreamConn(c), nil
}
  • Servers: Accept(ctx, conn, opts) reads the request itself; AcceptRequest(ctx, conn, br, req, opts) takes one already read with httphead, with the reader that holds what the client sent after it, so that one port can serve WebSocket and plain HTTP; CheckRequest and Handshake.Accept split the two steps, as wshttp.Upgrade(w, r, opts) does, which answers refusals through the ResponseWriter, hijacks on success, sends the fields of w.Header() with the 101 response and lets the handler return. wshttp.Check(w, r, opts) and wshttp.Accept(w, r, hs) are its two steps for a handler that decides on a valid request before anything is answered, such as by its subprotocol or an authorization: Check writes nothing, and a refusal or a decision against the request leaves the handler free to serve it as another request. Refused requests get 400, 403, 405, 426 (with Sec-WebSocket-Version: 13), 431, 500 (a response field of Header that cannot be sent) or 505, or the 4xx or 5xx status of a *HandshakeError from CheckOrigin. CheckOrigin defaults to same-origin and accepts requests without Origin; Subprotocols are chosen by the server's preference; Conn.Request() keeps the request, for authentication or the fields that carry a client address.
  • Clients: Client(ctx, conn, url, opts) runs the handshake over a connection the caller dialed, such as one through a proxy, already under TLS for wss; Dialer.Dial dials ws URLs with Forward and wss URLs with TLS, such as a tlsconn.Dialer, whose certificate verification is on unless its config turns it off, and fails with ErrNoTLSDialer without one. Host overrides the request's Host field, and Header adds fields; the handshake's own fields are refused. A refused handshake is a *HandshakeError with the status and the response.
  • Handshakes are bounded by the context, or HandshakeTimeout (10s), and close the connection on failure, as the other handshakes of this module do.
  • Messages: ReadMessage, AppendMessage (into a reused buffer, without allocating), NextReader, WriteMessage, WriteMessages (a batch, framed as WriteMessage frames each message, in one write and with no frame of another message or control frame between them) and NextWriter (frames of up to 32 KiB, or what a larger Write gets), text and binary. ReadLimit (4 MiB, after decompression) bounds messages: kept small because deflate inflates about 1000:1, so with compression a few kilobytes on the wire make a message of the limit; a StreamConn reads without it, as it holds no message in memory.
  • Concurrency: one goroutine reads; writes may come from any number of goroutines and are serialised frame by frame, with the frames of one message never interleaved with another's, while control frames go out between them. Pings are answered while reading, without waiting for a write in progress: the pong is queued and sent by the writer that holds the connection, or, when none does, by the reader within the close timeout and its read deadline, so that a peer that pings and never reads cannot hold the reader; such a pong is dropped. OnPing and OnPong observe them, such as to extend a read deadline. A peer that does not read stalls writes until the buffers fill, so servers that write, also only now and then, need write deadlines as well as read deadlines.
  • Close sends a close frame, waits for the peer's, reading and discarding messages itself when no read is in progress, and closes the connection, all within CloseTimeout (5s), also when a write is blocked, which then fails; so the connection does not end with a reset that could lose data in flight. A peer's close frame is answered at once and read as a *CloseError with its code and reason; the server then closes the connection beneath first. CloseWrite sends the close frame alone, as a half-close: no message can be written after it, and reads go on until the peer's close frame, which ends the connection. Abort(cause) ends the connection at once without a close frame, with a reset where it runs over TCP, so that the peer sees a cut; Relay uses it when it stops on an error.
  • StreamConn: each Write is one binary message of one frame, Read crosses message bounds and also takes text messages; close codes 1000, 1001 and none, and a peer that just closes the connection between frames, end the stream with io.EOF. Deadlines are the connection's; a read or write cut short by one leaves the connection usable, unless it wrote part of a frame, or of a fragmented message, or read part of a compressed message.
  • Writes: a server copies at most 32 KiB of a payload, a frame that fits the write buffer goes out with its header in one write and a larger one with writev on TCP and Unix connections; a client masks into the pooled write buffer. Idle connections hold only their read buffer (4 KiB).
  • Validation follows RFC 6455 strictly where a lax reading could be abused: reserved bits and opcodes, the masking direction, control frames of at most 125 bytes that are not fragmented, fragment order, close codes and UTF-8 in text messages (checked as it arrives) and close reasons fail the connection with 1002, 1007 or 1009. It is lenient where the RFC allows: non-minimal payload lengths, any letter case in handshake tokens, a missing Host field.
  • Compression: Compression{Level, Threshold} offers or accepts permessage-deflate without context takeover in both directions, so that a connection keeps no compressor state between messages; offers that need a window smaller than 32 KiB, which compress/flate cannot produce, are declined. Messages under Threshold (128 bytes) go out uncompressed.
  • WebSocket over HTTP/2 (RFC 8441): wshttp.Upgrade also accepts an extended CONNECT, answers it with 200 and runs the connection over the stream, many to one HTTP/2 connection. net/http accepts extended CONNECT only when the program starts with GODEBUG=http2xconnect=1 in its environment; without it everything is HTTP/1.1 as before. A stream lives only as long as its handler, so wshttp.Serve(w, r, opts, fn) runs fn and closes the connection when it returns, and with Upgrade the handler waits for wshttp.Done(c); the end of the stream or of the HTTP/2 connection closes the WebSocket connection. On a server's stream, an expired write deadline resets the stream and an expired read deadline ends its reading for good; on a client's stream either resets it. wshttp.Dialer dials over HTTP/2 with a Transport that can send the :protocol pseudo-field, which net/http's cannot, and falls back to HTTP/1.1 only through its HTTP1 dialer, within one handshake timeout; URL credentials go out as Basic on both. CheckRequest, Handshake.ResponseHeader, Handshake.NewConn, ClientOptions.ExtendedConnectHeader and ExtendedConnectClient serve other HTTP/2 stacks; NewConn wraps a connection whose handshake was done otherwise.
  • The masking keys and handshake keys come from the runtime's ChaCha8 generator, and the accept key's SHA-1 is computed in the package, as crypto/sha1 would add about 176 KB of FIPS code to a program (linux/amd64, stripped).

Upstream Proxies

github.com/djylb/netx/proxydial dials TCP through an HTTP CONNECT or SOCKS5 proxy. FromURL, FromString and FromEnvironment build the dialers from a URL; they are plain structs (HTTPDialer, socks5.Dialer) that can also be configured directly, for example with a private CA or extra request headers. To reach an encrypted proxy, supply a TLS transport such as tlsconn.Dialer.

func corporateProxy(ca *x509.CertPool) *proxydial.HTTPDialer {
	return &proxydial.HTTPDialer{
		ProxyAddr: "proxy.corp.example:3128",
		Header:    textproto.MIMEHeader{"User-Agent": {"my-agent/1.0"}},
		// TLS to the proxy, verified against its host name.
		Forward: &tlsconn.Dialer{
			Config:  &tls.Config{RootCAs: ca},
			Forward: &net.Dialer{Timeout: 10 * time.Second},
		},
	}
}
func dialVia(ctx context.Context, proxyURL, target string) (net.Conn, error) {
	forward := &net.Dialer{Timeout: 10 * time.Second}
	tlsProxy := proxydial.WithTLS(tlsconn.ProxyTLS(nil))
	var d netx.ContextDialer
	var err error
	if proxyURL != "" {
		// ParseURL and FromURL; a bare host:port is an http proxy.
		d, err = proxydial.FromString(proxyURL, forward, tlsProxy)
	} else {
		d, err = proxydial.FromEnvironment(forward, tlsProxy)
	}
	if err != nil {
		return nil, err
	}
	ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
	defer cancel()
	return d.DialContext(ctx, "tcp", target)
}
  • Schemes: http (port 80), https (port 443, TLS to the proxy), socks5, socks5h, socks4a and socks4 (port 1080), and socks5+tls, socks5h+tls, socks4a+tls and socks4+tls for SOCKS over TLS, verified against the proxy's host name. User information becomes the dialer's Username and Password: Basic Proxy-Authorization (unless Header sets that field, which then wins), SOCKS5 username/password or the SOCKS4 user ID. The SOCKS5 and SOCKS4a schemes let the proxy resolve host names; socks4 resolves them locally. A dialer for one proxy can be the Forward dialer of another, which chains them.
  • FromURL, FromString and FromEnvironment require WithTLS for https and +tls URLs. Without it they return proxydial.ErrNoTLSDialer. The factory wraps the dialer used to reach the proxy. It must honor the dial context and verify the proxy's identity. When no server name is configured, it derives the name from the proxy address passed to DialContext. tlsconn.ProxyTLS(nil) verifies against the system roots. Pass a *tls.Config to use private roots. The factory uses HandshakeTimeout: 0, which honors the context deadline when set and applies tlsconn.DefaultHandshakeTimeout when it has none. FromURL returns an *proxydial.HTTPDialer or a *socks5.Dialer. Type-assert it to adjust fields such as Header. When constructing either dialer directly, set its Forward field to the TLS dialer.
  • ParseURL parses a proxy URL leniently: proxy:3128 or 127.0.0.1:1080 without a scheme is an http proxy, and its errors never quote the password.
  • A refused CONNECT is a *proxydial.ConnectError with the status code, status text and reply header, so a caller can answer a 407 challenge from Proxy-Authenticate or tell 403 from 502.
  • HTTPDialer.Handshake runs CONNECT on a connection the caller already has to the proxy, such as a multiplexed stream. It returns that connection, or a netx.PrefixConn over it when the proxy sent tunnel bytes with its reply, and closes the connection on failure, as netx.DoHandshake does.
  • The dialers also have a Dial(network, address) method, for code that expects a dialer without a context.
  • The context bounds the dial, the TLS handshake with the proxy and the proxy handshake; the returned connection has no deadline. Bytes the HTTP proxy sends right after its 2xx reply are kept.
  • FromEnvironment reads ALL_PROXY only, with NO_PROXY, not HTTP_PROXY or HTTPS_PROXY: a TCP dialer does not know whether its target speaks HTTP or HTTPS, so HTTP clients should use http.ProxyFromEnvironment for those. ALL_PROXY is parsed with ParseURL, and targets in NO_PROXY bypass the proxy: *, IP addresses (IPv6 with or without brackets), CIDR ranges, and domain names, which also match their subdomains (a leading . or *. matches subdomains only). An entry may end in :port.
  • FromEnvironment returns the direct dialer when ALL_PROXY is unset, FromURL's dialer when NO_PROXY is empty, and otherwise a *proxydial.Bypass, whose Proxy field holds FromURL's dialer (b.Proxy.(*proxydial.HTTPDialer) to set Header). Bypass and ParseNoProxy also work with other dialers.

Destination Policies

github.com/djylb/netx/safedial dials, and sends datagrams to, only the destinations a policy allows, for a program that connects on behalf of a party it trusts less: a tunnel client that a server tells where to connect, a proxy, or a webhook sender. The check binds to the address actually dialed, so DNS rebinding and later re-resolution cannot get around it.

d := &safedial.Dialer{
	// nil Policy: DefaultPolicy, global unicast addresses only.
	Policy: safedial.All(
		safedial.DenyPorts(25),
		safedial.Any(
			// Names under corp.example may resolve to private addresses,
			// not to loopback, link-local (metadata) or other ones.
			safedial.All(
				safedial.AllowNames("corp.example"),
				safedial.AllowScopes(netx.ScopePrivate, netx.ScopeGlobal),
			),
			safedial.DefaultPolicy(),
		),
	),
}
client := &http.Client{Transport: &http.Transport{DialContext: d.DialContext}} // no Proxy

_, err := d.DialContext(ctx, "tcp", "127.1:6379")
var denied *safedial.DeniedError
if errors.As(err, &denied) { // errors.Is(err, safedial.ErrDenied) too
	log.Printf("refused %v: %v", denied.Target, denied.Reason) // 127.0.0.1:6379: loopback
}
  • Dialer is a netx.ContextDialer with Forward (zero net.Dialer if nil), Resolver (*net.Resolver or anything with LookupNetIP), Policy, Stagger and VerifyRemoteAddr. It parses the target with ParseTarget: IP literals in every form, bracketed, IPv4-mapped (unmapped), zoned (the zone kept apart, in Target.Zone, and used to dial) or with a trailing dot, are checked as addresses, and so are the legacy IPv4 forms that system resolvers read as addresses (127.1, 2130706433, 0x7f.0.0.1, 0177.0.0.1), parsed as inet_aton does (ParseLegacyIPv4). Hosts that are no plain host name, such as ones with spaces, non-ASCII bytes, a numeric last label or an empty host, fail with netx.ErrInvalidAddr before any resolver sees them.
  • A host name is checked by name first (so DenyNames refuses it without a lookup), resolved once, and every address is unmapped and checked; only the allowed ones are dialed, as IP literals, interleaved by family and raced through netx.RaceDialer.DialAny as Happy Eyeballs does. A name is never resolved twice per dial, CNAMEs do not matter since the final addresses are checked, and an HTTP client's redirects dial, and are checked, again. Lookup returns the addresses DialContext would dial. VerifyRemoteAddr closes a connection whose RemoteAddr is not the address dialed, for a Forward that might connect elsewhere.
  • Not covered: an upstream proxy that resolves names itself. Give an http.Transport that dials with a Dialer no Proxy; a proxy dialer as Forward receives IP addresses only, which reach what they reach from the proxy's network.
  • A Policy (Check(Target) error, or a PolicyFunc) sees a name before it is resolved (Addr invalid) and each address with the name. Building blocks: DefaultPolicy (AllowScopes(netx.ScopeGlobal): no loopback, private, link-local, shared CGNAT, unspecified, multicast, broadcast, documentation, benchmarking, reserved, nor NAT64/6to4/Teredo addresses embedding them), AllowScopes, DenyScopes, AllowPrefixes, DenyPrefixes (binary search over merged prefixes; an invalid prefix fails closed), AllowPorts, DenyPorts, AllowPortRange, DenyPortRange, AllowNames and DenyNames (example.com matches it and its subdomains, *.example.com only subdomains; internationalised patterns match in their punycode form, and a DenyNames pattern that is no host name refuses every name), All/Any to combine them, and WithEmbeddedIPv4, which judges an address that embeds IPv4 (NAT64, 6to4, IPv4-compatible) also as that IPv4 address, so that prefix rules hold under every spelling. An allowed name reaches whatever its DNS points to, so pair AllowNames with the scopes or prefixes its names may reach; name rules do not stop another name or an IP address that reaches the same host. A target with neither an address nor a name, such as a *net.UDPAddr without an IP, is always refused, as sockets send it to the local host. A refusal is a *DeniedError with the Target and the Reason (ErrScope, ErrPrefix, ErrPort, ErrName, ErrRemoteMismatch or the policy's own), matching ErrDenied.
  • UDP: DialContext takes udp, udp4 and udp6. For relays that send to many destinations, WrapPacketConn wraps a net.PacketConn (checking WriteTo and WriteToUDPAddrPort) and WrapAddrPacketConn a socks5.PacketConn-shaped connection, which the result is too, so it fits a socks5.Server's DialPacket or a DatagramRelay. Replies from any source are delivered (full cone). Names are resolved by the wrapper itself, never by the wrapped connection: cached for a minute (failures five seconds, 1024 names), and datagrams wait for a lookup without blocking WriteTo, within 64 lookups, 16 datagrams per name and 256 KiB (ErrLookupBusy beyond). Close cancels the lookups.
  • Checking an IP destination, with Dialer.Check or a datagram through either wrapper, does not allocate with the policies of this package.

In-memory network for tests

github.com/djylb/netx/memnet is a network inside the process, for tests of code that dials, listens and resolves through an injected network:

n := memnet.New()
n.Clock = fake // a timeshim.Clock for the link delays
n.SetHost("svc.test", netip.MustParseAddr("10.0.0.1"))
l, _ := n.Listen(ctx, "tcp", "10.0.0.1:80")
c, _ := n.From(netip.MustParseAddr("192.0.2.7")).Dial(ctx, "tcp", "10.0.0.1:80")
n.SetLink("10.0.0.1:80", memnet.LinkPair{To: memnet.Link{Delay: 50 * time.Millisecond}})
  • Streams behave like TCP sockets: 256 KiB buffered in each direction, so both ends may write at once (unlike net.Pipe), CloseWrite half-closes, SetLinger(0) makes Close a reset (ECONNRESET for the peer), and deadlines end blocked calls with os.ErrDeadlineExceeded. Pipe gives a pair without a network.
  • Packet endpoints deliver whole datagrams through bounded queues and drop them when full or when nothing listens, as UDP does.
  • Dial to no listener fails with ECONNREFUSED. DialFrom and From set the source host, with an ephemeral port, on both ends.
  • SetLink sets per address and direction a delay, a rate, a datagram loss (drawn from Rand) or Off, which refuses dials, drops datagrams and closes the open connections. Delays and rates run on Clock.
  • LoopbackUDP opens a real UDP socket on 127.0.0.1 with an ephemeral port that no IPv4 wildcard socket shares.

Documentation

Overview

Package netx provides reusable networking helpers for Go.

The root package holds portable connection helpers:

  • Connection wrappers: TimeoutConn (idle timeout), FramedConn (length-prefixed messages as a stream or as datagrams), PrefixConn (replays bytes already read), RecordingConn (records reads), AddrOverrideConn, WrapConn and ObserveConn (traffic callbacks). The wrappers pass CloseWrite on, and InnermostConn and ConnAs unwrap them, and any connection with a NetConn method such as *tls.Conn. Peek and PeekFull read the first bytes of a connection and replay them.
  • Relay copies between two connections in both directions until its context ends, optionally passing half-closes on, ending idle relays, and pacing and counting each direction through RelayFlow hooks; Copy copies one direction the same way. RelayEnd and ChainReader relay parts of connections, such as one exchange of a protocol, splicing an *io.LimitedReader over a connection. ConnGroup closes connections and relays together. DoWithContext bounds a blocking call on a connection with a context, and DoHandshake an exchange that closes the connection when it fails, as the handshakes of this module do.
  • Addr is a destination as proxy requests name it, an IP address or a host name and a port, normalised so that policies see one form.
  • Dialing: DialFirst returns the first of several dial attempts that connects, and RaceDialer races several dialers as a ContextDialer, or the addresses of a service with DialAny.
  • Listeners: ChanListener accepts connections that the program delivers or dials in memory, NewSingleConnListener serves one connection, and ListenEphemeralUDP opens a UDP socket on a free port. Accept retries temporary Accept errors with a backoff. See udpflow.ListenUDPReusePort for UDP socket groups using SO_REUSEPORT.
  • Error classification: IsTimeout, IsClosed, IsConnReset, IsConnRefused and the other Is* helpers, NetErrorKind and NetErrorDetails. They match platform errnos, including Winsock codes on Windows, before English error text.

Protocol and platform helpers live in subpackages:

  • duplex joins a read half and a write half into one connection.
  • forwarded interprets client metadata from trusted proxies.
  • httphead parses HTTP/1.x heads and body framing.
  • httpproxy serves HTTP forward proxies and CONNECT tunnels.
  • httprewrite applies HTTP header and redirect rewrite rules.
  • memnet provides in-process streams and datagrams for tests.
  • proxydial dials through HTTP CONNECT, SOCKS5 and SOCKS4 proxies, with caller-supplied TLS for encrypted proxy connections.
  • proxyproto builds, decodes and serves PROXY protocol headers.
  • safedial dials and relays datagrams under a destination policy.
  • socks5 implements SOCKS5 and SOCKS4 clients and servers.
  • tlsconn runs bounded TLS handshakes and handles certificates.
  • transparent accepts transparently redirected TCP and UDP flows.
  • udpflow demultiplexes packet sockets into datagram connections.
  • wsconn handles WebSocket handshakes, frames and stream adapters.
  • wsconn/wshttp integrates WebSockets with net/http.

The module uses the standard library and github.com/djylb/timeshim, which itself uses only the standard library. The only packages that bring in crypto/tls are tlsconn directly and httprewrite and wsconn/wshttp through net/http.

Settings use the documented default for zero fields, omitted functional options and optional nil constructor arguments. Defaults for timeouts and limits are bounded unless documented otherwise. An explicit zero passed to an option or constructor follows that parameter's documented rule. A negative timeout disables it unless the setting says otherwise. Other negative values require a documented meaning. Servers and dialers expose settings as fields. Helpers use functional options for optional settings and ordinary arguments for required inputs.

Index

Examples

Constants

View Source
const DefaultDialStagger = 300 * time.Millisecond

DefaultDialStagger is how long DialFirst waits for an attempt before it starts the next when stagger is 0.

View Source
const DefaultRecordingLimit = 64 * 1024

DefaultRecordingLimit is how many read bytes a RecordingConn records when NewRecordingConn is given no positive limit.

View Source
const MaxFramePayload = 65535

MaxFramePayload is the maximum payload size of one framed message.

View Source
const MaxNameLen = 255

MaxNameLen is the length of the longest host name an Addr holds, as DNS and SOCKS bound it.

Variables

View Source
var ErrFrameDesync = errors.New("netx: framed stream desynchronized by a partial frame")

ErrFrameDesync is returned after a read or write failed in a way that lost frame bytes, such as the end of the stream inside a frame (see FramedConn). Frame boundaries in that direction are lost, so the error is sticky and the connection should be closed. Use errors.Is to detect it. The returned error also wraps the failure that caused it, so errors.Is and errors.As still see that cause (an EOF inside a frame as io.ErrUnexpectedEOF), except that a timeout cause is hidden and the error never reports a timeout.

View Source
var ErrFrameTooLarge = errors.New("netx: frame size exceeds MaxFramePayload")

ErrFrameTooLarge is returned by WriteFrame, and by Write in datagram mode, for a payload longer than MaxFramePayload.

View Source
var ErrGroupClosed = errors.New("netx: connection group closed")

ErrGroupClosed is returned by ConnGroup.Add on a group that Close closed.

View Source
var ErrInvalidAddr = errors.New("netx: invalid address")

ErrInvalidAddr reports an address that cannot be parsed or encoded.

View Source
var ErrNoDialAttempts = errors.New("netx: nothing to dial")

ErrNoDialAttempts is returned by DialFirst without attempts and by RaceDialer.DialAny without addresses.

View Source
var ErrRelayGroupClosed = errors.New("netx: relay closed by its group")

ErrRelayGroupClosed is returned by a Relay that a ConnGroup closed; see WithRelayGroup.

View Source
var ErrRelayIdle = errors.New("netx: relay idle")

ErrRelayIdle is returned by a Relay that WithRelayIdleTimeout ended.

View Source
var ErrWouldBlock error = wouldBlockError{}

ErrWouldBlock is returned by ReadNotifier.TryRead when the source holds nothing to read yet and has neither ended nor failed. It also ends an io.ReaderFrom that Relay feeds only while its source has data; see Relay. Its WouldBlock method reports true, so IsWouldBlock recognizes it; a source may return an error of its own instead.

Functions

func Abort

func Abort(c io.Closer, cause error)

Abort ends c abnormally, so that its peer reads an error, not an end of data: an Aborter, c itself or the first one beneath its wrappers, as reached through owned connections, is aborted with cause; otherwise a *net.TCPConn beneath c gets SO_LINGER 0, so that closing it sends RST instead of FIN. Then c is closed, unless it is an Aborter itself. A connection with neither is just closed, as a *net.UnixConn or a datagram connection, whose peers cannot tell the two apart.

func Accept

func Accept(ctx context.Context, l net.Listener) (net.Conn, error)

Accept waits for the next connection of l. It calls l.Accept again after the errors for which IsAcceptRetryable reports true: at once after the first, as such an error concerns one connection, and then, while they persist, after a delay that doubles from 1ms up to 1s, so that a server out of file descriptors does not spin. It returns the first other error, such as that of a closed listener, or ctx's error when ctx ends while it waits to retry. ctx does not end a blocked l.Accept; close l for that.

func CloseBeneathTLS

func CloseBeneathTLS(c net.Conn)

CloseBeneathTLS closes the connection beneath c when c is a TLS connection. Call it before closing c after an exchange over c timed out or was canceled, as DoHandshake does: a TLS connection whose write was cut short would still send close_notify on Close, under a record number that the peer cannot authenticate, so the peer would see a TLS failure instead of the end of the connection. With the connection beneath closed, c's Close sends nothing.

A TLS connection is one with the NetConn and HandshakeContext methods of *tls.Conn, so that this package does not link crypto/tls and the connections of other TLS implementations can declare their transport with NetxOwned. Only the transport owned by c is closed.

func ConnAs

func ConnAs[T any](v any) (T, bool)

ConnAs returns the first connection of type T in the chain beneath v, v included, as errors.As does for errors: through the wrappers of this package and NetConn methods, such as to find the *tls.Conn or *TimeoutConn beneath other wrappers.

func Copy

func Copy(ctx context.Context, dst io.Writer, src io.Reader, f *RelayFlow) (int64, error)

Copy copies src to dst until src's EOF or an error, as one direction of a Relay does, with the same splicing, waiting without a buffer and handling of datagrams, paced and counted by f, which may be nil for neither. It closes neither end and returns the bytes copied and nil at EOF, or the error that stopped it; f.End is called before it returns.

ctx ends a blocked f.Wait, and, since Copy does not close the ends, once ctx is done Copy sets an expired read deadline on src and an expired write deadline on dst, those that have SetReadDeadline and SetWriteDeadline, to interrupt a blocked read or write, and returns context.Cause(ctx); the deadlines stay set for the caller to reset. A source or destination without deadlines must be closed to end a Copy blocked on it.

func DialFirst

func DialFirst(ctx context.Context, stagger time.Duration, attempts ...func(context.Context) (net.Conn, error)) (net.Conn, int, error)

DialFirst runs attempts, which may dial in different ways, such as directly and through a relay, and returns the first connection made and the index of the attempt that made it. It starts them in order, starting the next while earlier ones go on whenever one has not connected within stagger, or at once when one fails; a stagger of 0 means DefaultDialStagger, and a negative one starts the next only when one fails, as a negative net.Dialer.FallbackDelay does. The other attempts are cancelled, and connections they still make are closed.

When none connects, it returns -1 and the errors of every attempt, joined, or ctx's error when ctx ended the dial. An attempt that returns a connection with an error fails, and its connection is closed.

func DoHandshake

func DoHandshake(ctx context.Context, c net.Conn, fn func() error) error

DoHandshake runs fn, an exchange on c that c is no use without, such as a proxy handshake, bounded by ctx as with DoWithContext, and closes c when it fails: c belongs to the caller after a success and is closed after a failure, the rule that every handshake of this module follows. When ctx ended the exchange or its I/O timed out, a write may have been cut short, so the connection beneath a TLS c is closed first, as by CloseBeneathTLS, and closing c sends no close_notify that the peer cannot authenticate.

func DoWithContext

func DoWithContext(ctx context.Context, c net.Conn, fn func() error) error

DoWithContext runs fn, which does I/O on c, such as reading a request, bounded by ctx: ctx's deadline becomes c's deadline, and once ctx is done c's deadline is set in the past to interrupt the I/O. For a cancelable ctx, a connection that rejects a deadline returns an error before fn starts. When fn returns, c's deadline is cleared. It returns ctx's error when ctx ended fn, also context.DeadlineExceeded when c's deadline, which is ctx's, expired just before ctx reported it, and otherwise fn's error.

As an I/O helper it leaves c open on failure, as Peek does, since a failure need not end the connection, such as a sniffing read that times out before a client that waits for the server to speak first. For an exchange that c is no use without, such as a protocol handshake, use DoHandshake, which closes c on failure as the handshakes of this module do.

func EmbeddedIPv4

func EmbeddedIPv4(a netip.Addr) (netip.Addr, bool)

EmbeddedIPv4 returns the IPv4 address that a carries in its IPv6 form, the address that a translator or relay on the path delivers to: an IPv4-mapped address (::ffff:a.b.c.d), the NAT64 well-known prefix 64:ff9b::/96 (RFC 6052), the NAT64 local-use prefix 64:ff9b:1::/48 in the RFC 6052 /48 layout (RFC 8215), 6to4 2002::/16 (RFC 3056) and the deprecated IPv4-compatible form ::a.b.c.d (RFC 4291), apart from :: and ::1, which are IPv6's own. It reports false for an IPv4 address and for an IPv6 address of any other form; a Teredo address carries two IPv4 addresses, and ScopeOf judges both. The zone is ignored.

A policy that judges addresses by range should judge an address that embeds IPv4 also by the embedded address, so that the same host cannot be reached under another spelling.

func ErrnoName

func ErrnoName(err error) string

ErrnoName returns the POSIX name of the platform errno in err's chain for the errnos that the classifiers know, such as ECONNRESET also for WSAECONNRESET, or "".

func InnermostConn

func InnermostConn(v any) net.Conn

InnermostConn returns the innermost connection beneath v: it follows the wrappers of this package and the NetConn() net.Conn methods of others, such as *tls.Conn's, which return the connection one layer down. It returns v itself when v wraps nothing, and nil for a nil connection, also a nil pointer such as a nil *net.TCPConn, and for a value that is not a connection. The connection is borrowed: v's owner still closes it.

func IsAcceptRetryable

func IsAcceptRetryable(err error) bool

IsAcceptRetryable reports whether err, returned by a listener's Accept, is worth calling Accept again for, as net/http decides: a timeout, or an error that reports itself temporary, such as running out of file descriptors (EMFILE, ENFILE) or a connection that the client aborted before it was accepted (ECONNABORTED). An error of a closed listener is not.

func IsAddrInUse

func IsAddrInUse(err error) bool

IsAddrInUse reports whether err looks like an address already in use, as when a listener's port is taken.

func IsAddrNotAvailable

func IsAddrNotAvailable(err error) bool

IsAddrNotAvailable reports whether err looks like an address that is not available on this host, as when binding to an address of another host.

func IsBrokenPipe

func IsBrokenPipe(err error) bool

IsBrokenPipe reports whether err looks like a broken pipe.

func IsCanceled

func IsCanceled(err error) bool

IsCanceled reports whether err comes from a canceled context or operation: context.Canceled, which a canceled dial or lookup of package net matches, or the "operation was canceled" text that some wrappers pass on without the error value.

func IsClosed

func IsClosed(err error) bool

IsClosed reports whether err comes from using a closed connection or listener: net.ErrClosed, io.ErrClosedPipe, or the "use of closed network connection" text that some wrappers pass on without the error value.

func IsConnAborted

func IsConnAborted(err error) bool

IsConnAborted reports whether err looks like an aborted connection.

func IsConnRefused

func IsConnRefused(err error) bool

IsConnRefused reports whether err looks like a refused connection attempt.

func IsConnReset

func IsConnReset(err error) bool

IsConnReset reports whether err looks like a connection reset.

func IsDNSError

func IsDNSError(err error) bool

IsDNSError reports whether err is a failed name lookup: a *net.DNSError in the chain.

func IsDNSNotFound

func IsDNSNotFound(err error) bool

IsDNSNotFound reports whether err is a lookup of a name or record that does not exist, as opposed to a failure to ask, such as a timeout.

func IsGlobal

func IsGlobal(a netip.Addr) bool

IsGlobal reports whether a is globally reachable unicast, ScopeOf(a) == ScopeGlobal: not private, shared, loopback, link-local, multicast, documentation, benchmarking, reserved or unspecified.

func IsHostUnreachable

func IsHostUnreachable(err error) bool

IsHostUnreachable reports whether err looks like an unreachable host. A failed lookup is KindDNS for NetErrorKind, whatever its cause; IsDNSError tells it apart.

func IsMessageTooLarge

func IsMessageTooLarge(err error) bool

IsMessageTooLarge reports whether err looks like a datagram too large to send or receive whole.

func IsNetworkUnreachable

func IsNetworkUnreachable(err error) bool

IsNetworkUnreachable reports whether err looks like an unreachable network.

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied reports whether err looks like a permission failure (EACCES or EPERM), such as a connect blocked by a local firewall rule.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout reports whether err is a timeout. It matches ETIMEDOUT (WSAETIMEDOUT on Windows) anywhere in the chain first, then the first net.Error's Timeout method, and only then English timeout messages.

func IsWouldBlock

func IsWouldBlock(err error) bool

IsWouldBlock reports whether err, or an error it wraps, has a method WouldBlock() bool that reports true, as ErrWouldBlock does: the error says that a read found nothing yet, not that it failed. A source can so signal it without depending on this package.

func ListenEphemeralUDP

func ListenEphemeralUDP(ctx context.Context, lc *net.ListenConfig) (*net.UDPConn, error)

ListenEphemeralUDP opens a UDP socket on a free port of every local address, with lc, nil meaning a zero net.ListenConfig, so that its Control can set socket options, for IPv4 and IPv6 where the system has both, as net.ListenUDP("udp", nil) does. On macOS and iOS, that call can take a port that another socket holds on one IPv4 address, such as 127.0.0.1, which then receives the datagrams sent to that address and port; this function takes a port free for IPv4 instead, and falls back to that call when it finds none, as when the IPv4 ports run out.

func ObserveConn

func ObserveConn(conn net.Conn, onRead, onWrite func(n int64) error) net.Conn

ObserveConn wraps conn and reports the bytes of each successful read to onRead and of each write to onWrite, either of which may be nil. An error from one is joined to the error of that Read or Write, so that it can end the connection's use, such as when an allowance runs out. With neither, conn is returned as it is.

To count and pace a Relay, use WithRelayFlows instead: a Relay cannot splice through, or wait for data without a buffer on, a connection that ObserveConn wraps.

func Peek

func Peek(ctx context.Context, c net.Conn, n int) (net.Conn, []byte, error)

Peek reads the first bytes of c, at most n, as for sniffing the protocol of a connection before it is handed on, and returns them with a connection that replays them before the rest of c. It returns after the first read that brings data, so a peer whose first message is shorter than n does not stall it; use PeekFull for exactly n bytes. ctx bounds the wait as DoWithContext does: its deadline becomes c's, and c's deadline is cleared again when Peek returns. The error is that of the read, or ctx's; c is left open and the returned connection is valid also then, so that a read that times out before a peer that waits for the server to speak first can still hand the connection on.

On a connection whose Reads return one datagram each, such as one of a PacketListener, Peek reads the first datagram whole, returns up to n of its bytes, and the returned connection replays the whole datagram, so that sniffing does not cut it short.

Example

Hand a connection on after sniffing its first bytes.

package main

import (
	"context"
	"fmt"
	"io"
	"net"

	"github.com/djylb/netx"
)

func main() {
	client, server := net.Pipe()
	go func() {
		_, _ = client.Write([]byte("GET / HTTP/1.1\r\n"))
		_ = client.Close()
	}()

	c, head, _ := netx.PeekFull(context.Background(), server, 4)
	fmt.Printf("%q\n", head)
	all, _ := io.ReadAll(c) // the next reader sees the whole request
	fmt.Printf("%q\n", all)
}
Output:
"GET "
"GET / HTTP/1.1\r\n"

func PeekFull

func PeekFull(ctx context.Context, c net.Conn, n int) (net.Conn, []byte, error)

PeekFull is Peek reading exactly n bytes, or fewer if a read fails first. On a datagram connection it reads one datagram, as Peek does.

func Relay

func Relay(ctx context.Context, a, b io.ReadWriteCloser, opts ...RelayOption) (aToB, bToA int64, err error)

Relay copies data between a and b in both directions and closes both when it returns. By default it stops as soon as either direction stops, at EOF or on an error, ending both ends to end the other direction; see WithRelayHalfClose.

Only a normal end, EOF, is passed on as an end of data: Relay then closes both ends, or with WithRelayHalfClose shuts down the writing side of the other end. Any other stop, an error in either direction, such as a reset by a peer or an error of a RelayFlow hook, the end of ctx, the idle timeout or a ConnGroup, aborts both ends with Abort instead, a *net.TCPConn with RST and an Aborter with its Abort, so that neither peer takes a cut transfer for a complete one.

The end of ctx stops the relay too, aborting both ends, and Relay then returns context.Cause(ctx), unless it had stopped already: cancel a context that many relays share, with a cause, to end them all, for example when an allowance runs out or a service is disabled; relays blocked in a read end too, which an error from RelayFlow.Done cannot do. A ctx that is done already passes no byte.

It returns the bytes copied from a to b and from b to a, and the error that stopped the relay, or nil if it stopped at EOF. The failure of a direction is a *RelayError, which tells which end's data was being copied, so that a caller can close each end with a cause of its own; the end of ctx, the idle timeout and a ConnGroup stop it with their own errors, as described above. Errors caused by Relay closing the connections are not reported.

On Linux and Android, a direction between a *net.TCPConn and another *net.TCPConn or a *net.UnixConn is left to the kernel with splice, through a pipe that it holds only while data moves. Relay looks through PrefixConns, AddrOverrideConns, TimeoutConns, whose idle deadlines it then refreshes itself, and the connections of ConnGroup.Track and NewSingleConnListener, for splice and its other fast paths, but not through other wrappers. Otherwise a direction is copied with the reading end's WriteTo or else the writing end's ReadFrom, as io.Copy would, except those of *net.TCPConn, whose data goes through a pooled 32 KiB buffer instead. A stream read straight from a socket takes that buffer only once the socket is readable, on Unix systems, so that an idle relay holds none, and is fed to the writing end's ReadFrom only while it has data: once the socket would block, ReadFrom's read fails, ReadFrom returns, and it is called again when the socket is readable, so that what it takes for a read is not held while the direction is idle. ReadFrom must return the read error, as io.ReaderFrom does, and stay usable after it.

A direction from a ReadNotifier, such as a stream of a multiplexed connection, also beneath the wrappers above, is copied without a goroutine of its own: each notification starts a task that copies through the pooled buffer until TryRead would block, so that an idle relay between such a stream and a TCP connection keeps only the goroutine that called Relay, waiting for the TCP side. The rest of the prefix of a PrefixConn above the stream is readable at once: it is copied without waiting for the stream. A task blocked on a write holds the stream back, as a blocked copy would.

A source that returns one datagram per Read, such as a *net.UDPConn, a udpflow.PacketListener connection, a FramedConn with WithFramedDatagrams, or a connection of another package whose LocalAddr is on a datagram network (udp, ip, unixgram), has each datagram written whole with one Write, empty ones included. A PacketListener connection hands its queued datagrams over and a FramedConn reads each frame into a buffer that fits it, so that an idle relay holds no buffer and each datagram is copied once, and RelayFlow.Done may see more than Wait's n for one; other sources get a 64 KiB buffer, the largest UDP datagram.

Example

Forward a client to an echo backend.

package main

import (
	"context"
	"fmt"
	"io"
	"net"

	"github.com/djylb/netx"
)

func main() {
	client, front := net.Pipe()
	back, backend := net.Pipe()
	go func() { _, _ = io.Copy(backend, backend) }()

	done := make(chan struct{})
	go func() {
		up, down, err := netx.Relay(context.Background(), front, back)
		fmt.Println(up, down, err)
		close(done)
	}()

	_, _ = client.Write([]byte("ping"))
	buf := make([]byte, 4)
	_, _ = io.ReadFull(client, buf)
	fmt.Println(string(buf))
	_ = client.Close()
	<-done
}
Output:
ping
4 4 <nil>

func WrapConn

func WrapConn(rwc io.ReadWriteCloser, parent net.Conn, opts ...WrapOption) net.Conn

WrapConn exposes rwc as a net.Conn using parent for addresses and deadlines. A nil parent is rwc itself when it is a net.Conn, so that its own wrappers keep their addresses and deadlines, and otherwise the connection beneath it. Closing the returned connection closes rwc. Use WithWrapParentClose to also close parent. When rwc is a ReadNotifier, so is the returned connection.

Types

type Aborter

type Aborter interface {
	Abort(cause error)
}

Aborter is a connection that can end abnormally, so that its peer sees a cut instead of an end of data: a stream of a multiplexed connection resets itself, a WebSocket connection drops its transport without a closing handshake. Abort ends both directions at once, ends the reads and writes that block on the connection and releases it as Close does; a Close afterwards must be harmless. cause tells why, for the connection's own reporting, and may be nil.

Abort and Relay use it, also beneath the wrappers of this package, TLS, and wrappers declaring OwnedLayers; a *net.TCPConn needs none, as it is reset with SO_LINGER 0.

type Addr

type Addr struct {
	IP   netip.Addr
	Name string
	Port uint16
}

Addr is a destination as proxy requests name it: an IP address or a host name, and a port. When IP is valid it is used and Name is ignored. The zero Addr stands for no address and prints as "0.0.0.0:0".

The constructors of this module put every IP address in IP, in one form: an IPv4-mapped IPv6 address as IPv4, without a zone, also when it comes as a name that is an IP literal, such as "127.0.0.1" or "::1", or one with a trailing dot, such as "127.0.0.1.", which some resolvers connect to as that address; and names in lower case, with a trailing dot kept. Names are not resolved. A policy on IP addresses that sees an Addr, such as a proxy server's Allow hook, must therefore also check the addresses that names resolve to, where they are dialed, for example with a net.Dialer Control function, since some resolvers turn legacy forms such as "127.1" or "0x7f.0.0.1" into addresses. The unspecified addresses 0.0.0.0 and :: reach the local host on many systems.

func AddrFromAddrPort

func AddrFromAddrPort(ap netip.AddrPort) Addr

AddrFromAddrPort returns the Addr of ap, normalised as described at Addr.

Example

Convert the source of a datagram, as net.UDPConn.ReadFromUDPAddrPort returns it, to an Addr; an IPv4 peer of a dual-stack socket comes as an IPv4-mapped IPv6 address, and a link-local one with a zone.

package main

import (
	"fmt"
	"net/netip"

	"github.com/djylb/netx"
)

func main() {
	fmt.Println(netx.AddrFromAddrPort(netip.MustParseAddrPort("[::ffff:192.0.2.1]:53")))
	fmt.Println(netx.AddrFromAddrPort(netip.MustParseAddrPort("[fe80::1%eth0]:5353")))
}
Output:
192.0.2.1:53
[fe80::1]:5353

func AddrFromNetAddr

func AddrFromNetAddr(a net.Addr) Addr

AddrFromNetAddr converts a *net.TCPAddr, a *net.UDPAddr, an Addr, or another net.Addr whose String is "host:port". It returns the zero Addr for nil, a nil pointer or an address it cannot split.

func HostAddr

func HostAddr(host string, port uint16) Addr

HostAddr returns the Addr of host, an IP literal or a name, and port, normalised as described at Addr. It does not check that a name is valid.

func ParseAddr

func ParseAddr(s string) (Addr, error)

ParseAddr parses "host:port", where host is an IP literal, IPv6 in brackets, or a name of at most MaxNameLen bytes, normalised as described at Addr.

func (Addr) Host

func (a Addr) Host() string

Host returns the IP address as text, or the name, or "0.0.0.0" for neither.

func (Addr) IsZero

func (a Addr) IsZero() bool

IsZero reports whether a is the zero Addr.

func (Addr) Network

func (a Addr) Network() string

Network returns "", as an Addr names no network, so that an Addr is also a net.Addr, such as for a source that is a name.

func (Addr) String

func (a Addr) String() string

String returns the address as "host:port", with an IPv6 address in brackets, for net.Dial.

type AddrOverrideConn

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

AddrOverrideConn is a net.Conn that reports overridden local and remote addresses. A nil override falls back to the wrapped connection's address.

func NewAddrOverrideConn

func NewAddrOverrideConn(c net.Conn, local, remote net.Addr) *AddrOverrideConn

NewAddrOverrideConn wraps c and overrides its local or remote address, in the order of LocalAddr and RemoteAddr; a nil address keeps c's own.

func (*AddrOverrideConn) Close

func (c *AddrOverrideConn) Close() error

Close implements net.Conn.

func (*AddrOverrideConn) CloseWrite

func (c *AddrOverrideConn) CloseWrite() error

CloseWrite shuts down the writing side of the wrapped connection; see TimeoutConn.CloseWrite.

func (*AddrOverrideConn) LocalAddr

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

LocalAddr implements net.Conn.

func (*AddrOverrideConn) NetConn

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

NetConn returns the connection that c wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs.

func (*AddrOverrideConn) NetxOwned

func (c *AddrOverrideConn) NetxOwned() OwnedLayers

NetxOwned describes the children closed with this layer.

func (*AddrOverrideConn) Read

func (c *AddrOverrideConn) Read(b []byte) (int, error)

func (*AddrOverrideConn) RemoteAddr

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

RemoteAddr implements net.Conn.

func (*AddrOverrideConn) SetDeadline

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

SetDeadline implements net.Conn.

func (*AddrOverrideConn) SetReadDeadline

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

SetReadDeadline implements net.Conn.

func (*AddrOverrideConn) SetWriteDeadline

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

SetWriteDeadline implements net.Conn.

func (*AddrOverrideConn) Write

func (c *AddrOverrideConn) Write(b []byte) (int, error)

func (*AddrOverrideConn) WriteTo

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

WriteTo copies the wrapped connection to w, through its own WriteTo when it has one, so a *net.TCPConn can still splice.

type ChainReader

type ChainReader struct {
	Next func() (io.Reader, error)
	// contains filtered or unexported fields
}

ChainReader reads the parts that Next returns one after another, as io.MultiReader does, but lazily: Next is called for the first part, and for the next one each time a part reaches EOF, until it returns a nil part, so that what follows can depend on what came before, as an HTTP body depends on its head. Relay and Copy copy each part as they would copy it as a source of its own, so that a part that is a connection, or an *io.LimitedReader over one, is spliced where the connection would be. An error of Next ends the reading with it. A ChainReader is not safe for concurrent use.

func (*ChainReader) Read

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

type ChanListener

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

ChanListener is a net.Listener fed by the program instead of a socket. Deliver hands it a connection accepted elsewhere, and Dial connects to it through an in-memory pipe. Accept returns the connections in order. All methods are safe for concurrent use. The zero value is ready to use, as a ChanListener of NewChanListener(nil, 0).

Example

Serve HTTP on connections that never touch a socket.

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"

	"github.com/djylb/netx"
)

func main() {
	l := netx.NewChanListener(nil, 16)
	srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprint(w, "hello from ", r.RemoteAddr)
	})}
	go func() { _ = srv.Serve(l) }()
	defer func() { _ = srv.Close() }()

	client := &http.Client{Transport: &http.Transport{
		DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
			return l.Dial(ctx, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1), Port: 4000})
		},
	}}
	resp, err := client.Get("http://in-memory/")
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = resp.Body.Close() }()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}
Output:
hello from 192.0.2.1:4000

func NewChanListener

func NewChanListener(addr net.Addr, queue int) *ChanListener

NewChanListener returns a ChanListener that reports addr from Addr and holds up to queue connections that Accept has not taken yet. A nil addr is reported as "pipe". With a non-positive queue, Deliver and Dial wait for Accept.

func (*ChanListener) Accept

func (l *ChanListener) Accept() (net.Conn, error)

Accept waits for the next queued connection. It returns net.ErrClosed once l is closed.

func (*ChanListener) Addr

func (l *ChanListener) Addr() net.Addr

Addr returns the address given to NewChanListener, or "pipe".

func (*ChanListener) Close

func (l *ChanListener) Close() error

Close stops l and closes the connections still queued. Blocked Accept, Deliver and Dial calls return net.ErrClosed. A nil listener returns net.ErrClosed. Concurrent and reentrant Close calls can return before the queue drains.

func (*ChanListener) Deliver

func (l *ChanListener) Deliver(ctx context.Context, c net.Conn) error

Deliver queues c for Accept, waiting for queue space until ctx is done or l is closed. On success l owns c: Accept returns it, or Close closes it. On failure it returns ctx.Err() or net.ErrClosed and c stays the caller's, to close or to hand elsewhere.

func (*ChanListener) Dial

func (l *ChanListener) Dial(ctx context.Context, remote net.Addr) (net.Conn, error)

Dial connects to l through a synchronous in-memory net.Pipe and returns the client end. The server end is queued as by Deliver. It reports remote as its RemoteAddr and l.Addr() as its LocalAddr, and the client end reports the reverse; a nil remote is reported as "pipe".

func (*ChanListener) TryDeliver

func (l *ChanListener) TryDeliver(c net.Conn) bool

TryDeliver queues c for Accept if the queue has room and l is open, and reports whether it did; l then owns c, as after Deliver. Otherwise c stays the caller's.

type ConnGroup

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

ConnGroup tracks connections, or anything else that closes, so that they can be closed together, such as every connection of one user when its allowance runs out or the service is disabled. A connection may be in several groups, such as those of its user, client and service, and a group may be in another: closing the members of the outer group closes those of the inner one, and closing the outer group closes the inner one. A Relay joins with WithRelayGroup, which also ends a RelayFlow.Wait that blocks. Its methods are safe for concurrent use. The zero value is an empty, open group.

Example

Close every connection of a group at once.

package main

import (
	"fmt"
	"net"

	"github.com/djylb/netx"
)

func main() {
	var user netx.ConnGroup
	a, b := net.Pipe()
	remove, _ := user.Add(a)
	defer remove()
	fmt.Println(user.Len())
	_ = user.CloseMembers(nil)
	_, err := b.Read(make([]byte, 1))
	fmt.Println(user.Len(), err)
}
Output:
1
0 EOF

func (*ConnGroup) Add

func (g *ConnGroup) Add(c io.Closer) (remove func(), err error)

Add adds c and returns a function that removes it again, which the owner of c calls once it is done with c, closed or not; calling it more than once is harmless. On a group that Close closed, Add returns ErrGroupClosed and leaves c to its owner. Add rejects nil members, including typed nils.

func (*ConnGroup) Close

func (g *ConnGroup) Close() error

Close closes the members of the group, as CloseMembers does but closing groups among them for good too, and makes Add refuse new members.

func (*ConnGroup) CloseMembers

func (g *ConnGroup) CloseMembers(cause error) error

CloseMembers closes the members of the group and removes them; the group takes new ones afterwards. Relays among them return cause too, if it is not nil, and groups among them close their own members the same way and stay open. It returns the errors of the members' Close methods, joined. The members are closed without the group's lock, so a Close that blocks, as a TLS connection's may, holds up neither Add nor removes.

func (*ConnGroup) Len

func (g *ConnGroup) Len() int

Len returns the number of members in the group: connections, groups, and relays that joined with WithRelayGroup.

func (*ConnGroup) Track

func (g *ConnGroup) Track(c net.Conn) (net.Conn, error)

Track adds c, as Add does, and returns c wrapped so that closing it also removes it from the group, which then needs no remove call. Relay looks through the wrapper as through c. On a group that Close closed, Track returns ErrGroupClosed and leaves c to its owner.

type ContextDialer

type ContextDialer = netutil.ContextDialer

ContextDialer dials connections with a DialContext(ctx, network, address) (net.Conn, error) method. *net.Dialer implements it, as do the dialers of the proxydial, socks5 and tlsconn packages. It is the same type as tlsconn.ContextDialer.

type ErrorKind

type ErrorKind string

ErrorKind is a stable category of a network error, for metrics and logs; see NetErrorKind.

const (
	KindNone               ErrorKind = "none"
	KindCanceled           ErrorKind = "canceled"
	KindDNS                ErrorKind = "dns"
	KindConnReset          ErrorKind = "conn_reset"
	KindConnAborted        ErrorKind = "conn_aborted"
	KindBrokenPipe         ErrorKind = "broken_pipe"
	KindConnRefused        ErrorKind = "conn_refused"
	KindHostUnreachable    ErrorKind = "host_unreachable"
	KindNetworkUnreachable ErrorKind = "network_unreachable"
	KindPermissionDenied   ErrorKind = "permission_denied"
	KindAddrInUse          ErrorKind = "addr_in_use"
	KindAddrNotAvailable   ErrorKind = "addr_not_available"
	KindMessageTooLarge    ErrorKind = "message_too_large"
	KindTimeout            ErrorKind = "timeout"
	KindUnexpectedEOF      ErrorKind = "unexpected_eof"
	KindEOF                ErrorKind = "eof"
	KindClosed             ErrorKind = "closed"
	KindOther              ErrorKind = "other"
)

The kinds that NetErrorKind returns, named after the classifier that matches each.

func NetErrorKind

func NetErrorKind(err error) ErrorKind

NetErrorKind returns the category of err: KindNone for nil, the kind of the first classifier that matches it, in the order of the constants, or KindOther.

type FramedConn

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

FramedConn reads and writes length-prefixed messages over a reliable stream.

Each frame is a 2-byte big-endian length followed by the payload. A frame is sent with one write of the connection, header and payload together (a vectored write on a *net.TCPConn), so a layer beneath, such as one that compresses or encrypts each write, sees whole frames; the bytes on the wire are the same however they are written.

By default the connection is a stream: Write sends p as one frame, or as several when it is longer than MaxFramePayload, which Reads join up again. Read it returns the current frame, or as much of it as fits in p, and a longer frame continues in the next Reads without being buffered. Empty frames are skipped, as they carry no stream bytes, and an error inside a frame splits it between two Reads.

With WithFramedDatagrams each frame is a message, as a datagram is: Write sends p as exactly one frame and fails with ErrFrameTooLarge for a longer one, and Read returns one frame per call. WriteFrame and ReadFrame work on one frame in either mode. WithFramedReadBuffer serves small frames or small buffers from one read of the connection.

An error that loses no frame bytes is returned unchanged and may be retried: one between frames or inside a frame header, such as an expired deadline, or, since stream Reads keep their place, one anywhere in a frame read by Read in stream mode. A ReadFrame or datagram Read that fails after part of the payload was read, the end of the stream inside a frame, and a write that fails after part of a frame was written lose the frame boundaries in that direction: they are reported as ErrFrameDesync wrapping their cause, which is not a timeout and is returned again by every later call in that direction.

Reads and writes may run concurrently with each other.

func NewFramedConn

func NewFramedConn(c net.Conn, opts ...FramedOption) *FramedConn

NewFramedConn wraps c with length-prefixed message I/O.

func (*FramedConn) Close

func (fc *FramedConn) Close() error

Close implements net.Conn.

func (*FramedConn) CloseWrite

func (fc *FramedConn) CloseWrite() error

CloseWrite shuts down the writing side of the wrapped connection after the frames written so far; see TimeoutConn.CloseWrite.

func (*FramedConn) LocalAddr

func (fc *FramedConn) LocalAddr() net.Addr

LocalAddr implements net.Conn.

func (*FramedConn) NetConn

func (fc *FramedConn) NetConn() net.Conn

NetConn returns the connection that fc wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs. Reading or writing it directly breaks the framing.

func (*FramedConn) NetxOwned

func (fc *FramedConn) NetxOwned() OwnedLayers

NetxOwned describes the children closed with this layer.

func (*FramedConn) Read

func (fc *FramedConn) Read(p []byte) (int, error)

Read reads frame payload into p.

In the default stream mode, a frame longer than p, or one whose reading an error interrupts, is returned across several Reads and empty frames are skipped; a Read that an error cuts short returns the bytes it read and leaves the error to the next Read. With WithFramedDatagrams, each call consumes exactly one frame, an empty one included, and discards what does not fit in p; an empty p consumes and discards one frame.

func (*FramedConn) ReadFrame

func (fc *FramedConn) ReadFrame() ([]byte, error)

ReadFrame reads and returns one complete frame. If Read has already partially consumed a frame, ReadFrame returns the remaining bytes.

func (*FramedConn) RemoteAddr

func (fc *FramedConn) RemoteAddr() net.Addr

RemoteAddr implements net.Conn.

func (*FramedConn) SetDeadline

func (fc *FramedConn) SetDeadline(t time.Time) error

SetDeadline implements net.Conn.

func (*FramedConn) SetReadDeadline

func (fc *FramedConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements net.Conn.

func (*FramedConn) SetWriteDeadline

func (fc *FramedConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements net.Conn.

func (*FramedConn) Write

func (fc *FramedConn) Write(p []byte) (int, error)

Write sends p as one frame. With stream reads, the default, a p longer than MaxFramePayload is sent as several frames, which the reader joins up again, so that io.Copy into a FramedConn works with any buffer; it returns the bytes of the frames sent whole. With WithFramedDatagrams, where each frame is a message, such a p fails with ErrFrameTooLarge, as WriteFrame does in both modes.

func (*FramedConn) WriteFrame

func (fc *FramedConn) WriteFrame(p []byte) error

WriteFrame writes one complete frame.

type FramedOption

type FramedOption func(*framedOptions)

FramedOption configures NewFramedConn.

func WithFramedDatagrams

func WithFramedDatagrams() FramedOption

WithFramedDatagrams makes each frame a message, as a datagram is: Read returns exactly one frame per call, discarding the bytes that do not fit in p like a UDP socket truncating a datagram, and Write sends exactly one frame, failing for a payload longer than MaxFramePayload. ReadFrame and WriteFrame are not affected.

func WithFramedReadBuffer

func WithFramedReadBuffer(size int) FramedOption

WithFramedReadBuffer reads the stream through a buffer of size bytes, so a burst of small frames costs one read of the wrapped connection instead of two per frame. Bytes already in the buffer are lost to anyone who reads the wrapped connection directly, for example through InnermostConn.

type NetErrorInfo

type NetErrorInfo struct {
	Kind      ErrorKind
	Err       string // err.Error()
	Local     string // the connection's local address
	Remote    string // the connection's remote address
	Op        string // of the *net.OpError in the chain
	Net       string
	Source    string
	Addr      string
	Syscall   string // of the *os.SyscallError in the chain
	ErrnoName string
	// Errno is the platform errno in the chain, 0 for none, and ErrnoName
	// its POSIX name for the errnos that the classifiers know (ECONNRESET
	// also for WSAECONNRESET, for example), which depends on neither the
	// platform nor the system language.
	Errno   int
	Timeout bool
}

NetErrorInfo describes a network error for diagnostics; see NetErrorDetails. Empty fields are not known.

func NetErrorDetails

func NetErrorDetails(err error, c net.Conn) NetErrorInfo

NetErrorDetails describes err, and the addresses of c if it is not nil, as fields, which String formats as one compact line for logs.

func (NetErrorInfo) String

func (i NetErrorInfo) String() string

String formats i as space-separated key=value fields, such as `kind=conn_reset err="..." remote=192.0.2.1:443 timeout=false errno=104 errno_name=ECONNRESET`.

type OwnedLayers

type OwnedLayers = netutil.Owned

OwnedLayers describes the children closed by a wrapper. An external wrapper can implement NetxOwned() OwnedLayers. Set Self to the wrapper itself and First and Second to the children its Close owns. Leave unused children nil. A NetConn method alone exposes a borrowed connection.

type PrefixConn

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

PrefixConn is a net.Conn whose reads return a prefix before the data of the connection it wraps. It hands a connection on after bytes were already read from it, for example to sniff the protocol. Writes, deadlines and addresses go to the wrapped connection.

func NewPrefixConn

func NewPrefixConn(c net.Conn, prefix []byte) *PrefixConn

NewPrefixConn returns c with prefix replayed before its own data. prefix is not copied and must not be modified afterwards.

func (*PrefixConn) Close

func (c *PrefixConn) Close() error

Close implements net.Conn.

func (*PrefixConn) CloseWrite

func (c *PrefixConn) CloseWrite() error

CloseWrite shuts down the writing side of the wrapped connection; see TimeoutConn.CloseWrite.

func (*PrefixConn) LocalAddr

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

LocalAddr implements net.Conn.

func (*PrefixConn) NetConn

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

NetConn returns the connection that c wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs. Reading it directly skips the rest of the prefix.

func (*PrefixConn) NetxOwned

func (c *PrefixConn) NetxOwned() OwnedLayers

NetxOwned describes the children closed with this layer.

func (*PrefixConn) Read

func (c *PrefixConn) Read(b []byte) (int, error)

func (*PrefixConn) RemoteAddr

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

RemoteAddr implements net.Conn.

func (*PrefixConn) SetDeadline

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

SetDeadline implements net.Conn.

func (*PrefixConn) SetReadDeadline

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

SetReadDeadline implements net.Conn.

func (*PrefixConn) SetWriteDeadline

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

SetWriteDeadline implements net.Conn.

func (*PrefixConn) Write

func (c *PrefixConn) Write(b []byte) (int, error)

func (*PrefixConn) WriteTo

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

WriteTo writes the rest of the prefix to w and then copies the wrapped connection to w, through its own WriteTo when it has one, so a *net.TCPConn can still splice.

type RaceDialer

type RaceDialer struct {
	// Dialers are the dialers to race, in order of preference; none means
	// a zero net.Dialer.
	Dialers []ContextDialer
	// Stagger is how long an attempt runs alone before the next one
	// starts, as in DialFirst; 0 means DefaultDialStagger (300ms), and a
	// negative value starts the next only when one fails, as for
	// net.Dialer.FallbackDelay.
	Stagger time.Duration
}

RaceDialer races dial attempts with DialFirst: DialContext dials one address through each of its dialers, such as directly and through a relay or several proxies, and DialAny dials each of several addresses of a service, such as the entry points of a cluster, through each dialer. It is a ContextDialer, so that it can stand where one goes, such as an http.Transport's DialContext or a proxy dialer's Forward. The zero RaceDialer, and a nil one, dial with a zero net.Dialer and DefaultDialStagger. Its fields must not change while it dials.

func (*RaceDialer) DialAny

func (d *RaceDialer) DialAny(ctx context.Context, network string, addresses ...string) (net.Conn, string, error)

DialAny dials addresses, in order of preference, through each of d's dialers, as DialFirst starts them: every dialer for the first address, then for the next. It returns the connection and the address that it connects to. When none connects, it returns ErrNoDialAttempts without addresses, ctx's error when ctx ended the dial, or else the errors of every attempt, joined, each naming its address.

func (*RaceDialer) DialContext

func (d *RaceDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)

DialContext dials address through each of d's dialers, as DialFirst starts them, and returns the first connection made. When none connects, it returns ctx's error when ctx ended the dial, or else the errors of every attempt, joined.

type ReadNotifier

type ReadNotifier interface {
	// TryRead reads as Read does but never blocks: while the source holds
	// no data and has not ended or failed, it returns 0 and an error for
	// which IsWouldBlock reports true: ErrWouldBlock, or an error of the
	// source's own, possibly wrapped, with a method WouldBlock() bool that
	// reports true. An error whose WouldBlock reports false is an ordinary
	// error, as is any other.
	// Otherwise it returns at once what Read would: n > 0 bytes, or 0 and
	// io.EOF at the end of the stream, or 0 and the error Read would
	// return. TryRead and Read share the source's data and are not called
	// concurrently with each other, as Reads are not.
	TryRead(p []byte) (n int, err error)

	// NotifyReadable arranges for f to be called once the source is
	// readable, and returns a function that cancels the call.
	//
	// f is called at most once, and exactly once unless stop cancels it
	// first: when data arrives, at the end of the stream, on an error or a
	// reset, when the source or the connection it belongs to is closed, and
	// when a read deadline passes. A source that is readable when
	// NotifyReadable is called calls f at once, without waiting for another
	// event, possibly on the calling goroutine before NotifyReadable
	// returns; a caller need not try TryRead first, and f must not wait for
	// NotifyReadable to return.
	//
	// f may run on any goroutine, such as the one that reads the
	// connection, and must not block; it may call the source's methods,
	// so the source must not hold a lock of its own while it calls f.
	//
	// stop cancels the call as the stop of context.AfterFunc does: it
	// returns true if it kept f from being called, and false if f has
	// already been called or started, or the call was stopped already. stop
	// does not wait for a running f to return, and calling it again is
	// harmless.
	//
	// A source need support only one pending call at a time: a caller
	// calls NotifyReadable again only after f has been called or stop
	// returned true. Changing the read deadline does not affect a pending
	// call beyond calling f when the deadline passes.
	NotifyReadable(f func()) (stop func() bool)
}

ReadNotifier is a source that can be read without blocking and that tells when it becomes readable, such as a stream of a multiplexed connection. Relay copies from it without a goroutine of its own: no goroutine waits while the source is idle, and a short task, started by the notification, copies what there is and ends once TryRead would block. Copy waits on it before it takes a buffer, so that an idle copy holds none.

The source is readable once TryRead would return anything but an error for which IsWouldBlock reports true: data, the end of the stream after the peer closed its writing side, or an error, such as for a reset, a local Close or CloseRead, or a read deadline that has passed.

type RecordingConn

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

RecordingConn records the bytes read from a connection, up to a limit, so that they can be replayed later, such as when a protocol was sniffed by reading it: Release returns the connection and the bytes, for a PrefixConn. For a single look at the first bytes, Peek is simpler.

func NewRecordingConn

func NewRecordingConn(c net.Conn, limit int) *RecordingConn

NewRecordingConn wraps c and records up to limit read bytes, DefaultRecordingLimit if limit is not positive.

func (*RecordingConn) Buffered

func (c *RecordingConn) Buffered() []byte

Buffered returns a copy of the bytes recorded so far.

func (*RecordingConn) Close

func (c *RecordingConn) Close() error

Close implements net.Conn.

func (*RecordingConn) CloseWrite

func (c *RecordingConn) CloseWrite() error

CloseWrite shuts down the writing side of the underlying connection; see TimeoutConn.CloseWrite.

func (*RecordingConn) Discard

func (c *RecordingConn) Discard()

Discard stops recording reads and frees what was recorded, such as once a sniffed protocol turned out not to need replaying.

func (*RecordingConn) LocalAddr

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

LocalAddr implements net.Conn.

func (*RecordingConn) NetConn

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

NetConn returns the connection that c wraps, or nil after Close or Release, as *tls.Conn's NetConn does; see InnermostConn and ConnAs.

func (*RecordingConn) NetxOwned

func (c *RecordingConn) NetxOwned() OwnedLayers

NetxOwned describes the children closed with this layer.

func (*RecordingConn) Read

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

func (*RecordingConn) Release

func (c *RecordingConn) Release() (net.Conn, []byte)

Release detaches the underlying connection and returns it with a copy of the buffered bytes. During an active Read it returns (nil, nil) and keeps ownership, so a read callback can try Release without blocking. Retry once the Read returns to include its bytes. After a transfer the RecordingConn reports net.ErrClosed from Read, Write and the deadline methods, and its Close does not close the returned connection.

func (*RecordingConn) RemoteAddr

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

RemoteAddr implements net.Conn.

func (*RecordingConn) SetDeadline

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

SetDeadline implements net.Conn.

func (*RecordingConn) SetReadDeadline

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

SetReadDeadline implements net.Conn.

func (*RecordingConn) SetWriteDeadline

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

SetWriteDeadline implements net.Conn.

func (*RecordingConn) Stop

func (c *RecordingConn) Stop()

Stop stops recording reads and keeps what was recorded, for Buffered and Release.

func (*RecordingConn) Truncated

func (c *RecordingConn) Truncated() bool

Truncated reports whether reads went past the limit, so that the recorded bytes are not all that was read.

func (*RecordingConn) Write

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

type RelayEnd

type RelayEnd struct {
	Reader io.Reader
	Writer io.Writer
	// CloseWriteFunc is called by CloseWrite, as with WithRelayHalfClose
	// when the direction into this end ends; nil calls the CloseWrite
	// method of Writer, if it has one.
	CloseWriteFunc func() error
	// CloseFunc is called by Close, as when the relay ends normally; nil
	// closes Reader and Writer where they are io.Closers.
	CloseFunc func() error
	// AbortFunc is called by Abort, as when the relay stops on an error or
	// because its context ended; it must end the reads and writes that
	// block on the end. nil aborts what Reader and Writer read and write
	// as Abort aborts a connection beneath its wrappers, an Aborter or a
	// *net.TCPConn, and then calls Close.
	AbortFunc func(cause error)
}

RelayEnd is an end of a Relay made of a reader and a writer, such as one side of a protocol exchange on a connection that carries more afterwards: Relay reads Reader and writes Writer as it would read and write them as ends of their own, looking through them for splice and its other fast paths, so that a part of a connection, such as an *io.LimitedReader over it or the parts of a ChainReader, is spliced where the connection would be. Reads, writes and closes go to the fields; it is not safe to change them while a Relay uses the end.

func (*RelayEnd) Abort

func (e *RelayEnd) Abort(cause error)

Abort calls AbortFunc, or aborts what Reader and Writer read and write and then calls Close; see Aborter.

func (*RelayEnd) Close

func (e *RelayEnd) Close() error

Close calls CloseFunc, or closes Reader and Writer. Values whose identity cannot be compared are closed separately.

func (*RelayEnd) CloseWrite

func (e *RelayEnd) CloseWrite() error

CloseWrite calls CloseWriteFunc, or the CloseWrite method of Writer.

func (*RelayEnd) Read

func (e *RelayEnd) Read(p []byte) (int, error)

func (*RelayEnd) Write

func (e *RelayEnd) Write(p []byte) (int, error)

type RelayError

type RelayError struct {
	From RelaySide
	Err  error
}

RelayError is the error of a Relay that the failure of one direction stopped: From is the end whose data that direction copied, so that the error is one of reading From, of writing From.Other(), or of the RelayFlow of that direction. Err is the error itself, which errors.Is and errors.As find through it. Whether it was the read or the write is told by Err where it is a *net.OpError; Relay does not take its fast paths apart to tell it otherwise.

func (*RelayError) Error

func (e *RelayError) Error() string

func (*RelayError) Unwrap

func (e *RelayError) Unwrap() error

Unwrap returns Err.

type RelayFlow

type RelayFlow struct {
	// Wait is called before each read from the direction's source with the
	// most bytes Relay can take at once, and blocks until bytes may pass. It
	// returns how many may pass now, from 1 to n: a stream is read for at
	// most that many, and a datagram is read whole, as it cannot be split.
	// On Unix systems, a source read straight from a socket is waited on
	// until it has data first, and its end is passed on without Wait; for
	// other sources Wait runs while they may still be idle, and before the
	// read that finds their end. A blocked Wait holds none of Relay's
	// buffers or pipes. A Wait that may block for long must return when ctx
	// is done: closing the relay's ends does not wake it, so end such relays
	// with Relay's context or WithRelayGroup.
	// Wait need not charge them, since Done reports what passed: a limiter
	// can charge that, going into debt that a later Wait waits out, so that
	// a relay idle in a read holds none of an allowance it shares. ctx is
	// done once the relay stops. An error ends the relay and is returned.
	Wait func(ctx context.Context, n int64) (int64, error)
	// Done is called with the bytes written to the direction's destination
	// after each write. An error, such as for a used up allowance, ends the
	// relay and is returned.
	Done func(n int64) error
	// First is called once with the first bytes read from the direction's
	// source, a stream's first non-empty read or the first datagram, before
	// they are written, so that a relay can tell the protocol of a
	// connection or log the start of it. b is valid only during the call.
	// A stream's first read goes through Relay's buffer, also where Relay
	// splices the rest.
	First func(b []byte)
	// End is called once when the direction stops, with the bytes it
	// copied and the error that stopped it: nil at the source's EOF, or
	// net.ErrClosed when the relay stopped it for another reason, such as
	// the other direction ending. Relay calls it before it passes the end on
	// with CloseWrite or stops the relay, so that the other direction can
	// be given a shorter idle timeout once one has ended, and Copy before it
	// returns. Unlike the other hooks, End alone does not make a direction
	// go through Relay's buffer.
	End func(n int64, err error)
}

RelayFlow paces and counts one direction of a Relay or a Copy. Any of its functions may be nil. They are called from the goroutine copying that direction, one call at a time; functions shared by both directions, or by several relays, as a limiter of one user is, must be safe for concurrent use.

type RelayOption

type RelayOption func(*relayOptions)

RelayOption configures Relay.

func WithRelayClock

func WithRelayClock(c timeshim.Clock) RelayOption

WithRelayClock makes the idle timeout of WithRelayIdleTimeout tell the time by c instead of the system clock, such as a timeshim.Fake in tests.

func WithRelayFlows

func WithRelayFlows(aToB, bToA *RelayFlow) RelayOption

WithRelayFlows paces and counts the two directions of a Relay, from a to b and from b to a; see RelayFlow. A nil flow does neither, and the flows are copied, so that changing them later does not affect the relay. A direction whose flow has Wait, Done or First is copied with splice where Relay would splice it, in pieces, so that Done sees the bytes as they pass, and otherwise through Relay's buffer: the reading end's WriteTo and the writing end's ReadFrom are not used, so only the sources that Relay knows to return one datagram per Read are read a datagram at a time.

Example

Count what a relay passes and end it from outside, as when an allowance runs out.

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net"

	"github.com/djylb/netx"
)

func main() {
	client, front := net.Pipe()
	back, backend := net.Pipe()
	go func() { _, _ = io.Copy(backend, backend) }()

	var counted int64
	count := netx.RelayFlow{Done: func(n int64) error {
		counted += n
		return nil
	}}
	ctx, cancel := context.WithCancelCause(context.Background())
	done := make(chan error)
	go func() {
		_, _, err := netx.Relay(ctx, front, back, netx.WithRelayFlows(&count, nil))
		done <- err
	}()

	_, _ = client.Write([]byte("ping"))
	_, _ = io.ReadFull(client, make([]byte, 4))
	cancel(errors.New("allowance used up"))
	err := <-done
	fmt.Println(err, counted)
}
Output:
allowance used up 4
Example (Limit)

Limit the bandwidth that a user's relays share.

package main

import (
	"context"
	"fmt"
	"io"
	"net"
	"sync"
	"time"

	"github.com/djylb/netx"
)

// byteLimiter is a shared bandwidth limit for RelayFlow: Done charges what
// passed, which may put the limiter in debt, and Wait waits the debt out, so
// a relay idle in a read holds none of the allowance. It is safe for
// concurrent use by many relays.
type byteLimiter struct {
	last   time.Time // under mu
	rate   float64   // bytes per second
	burst  float64
	tokens float64
	mu     sync.Mutex
}

func newByteLimiter(bytesPerSecond, burst int64) *byteLimiter {
	return &byteLimiter{rate: float64(bytesPerSecond), burst: float64(burst), tokens: float64(burst), last: time.Now()}
}

// refill adds the tokens earned since the last call; l.mu is held.
func (l *byteLimiter) refill(now time.Time) {
	l.tokens = min(l.burst, l.tokens+now.Sub(l.last).Seconds()*l.rate)
	l.last = now
}

// Wait blocks while the limiter is in debt and then lets up to n bytes pass.
func (l *byteLimiter) Wait(ctx context.Context, n int64) (int64, error) {
	for {
		l.mu.Lock()
		l.refill(time.Now())
		if l.tokens >= 1 {
			allowed := min(n, int64(l.tokens))
			l.mu.Unlock()
			return allowed, nil
		}
		wait := time.Duration((1 - l.tokens) / l.rate * float64(time.Second))
		l.mu.Unlock()
		t := time.NewTimer(wait)
		select {
		case <-ctx.Done():
			t.Stop()
			return 0, ctx.Err()
		case <-t.C:
		}
	}
}

// Done charges the bytes that passed.
func (l *byteLimiter) Done(n int64) error {
	l.mu.Lock()
	l.refill(time.Now())
	l.tokens -= float64(n)
	l.mu.Unlock()
	return nil
}

// Limit the bandwidth that a user's relays share.
func main() {
	user := newByteLimiter(64<<10, 16<<10) // 64 KiB/s, bursts of 16 KiB
	flow := netx.RelayFlow{Wait: user.Wait, Done: user.Done}

	client, front := net.Pipe()
	back, backend := net.Pipe()
	go func() { _, _ = io.Copy(io.Discard, backend) }()
	go func() { _, _, _ = netx.Relay(context.Background(), front, back, netx.WithRelayFlows(&flow, &flow)) }()

	start := time.Now()
	_, _ = client.Write(make([]byte, 48<<10)) // 16 KiB at once, then 32 KiB at 64 KiB/s
	_ = client.Close()
	fmt.Println(time.Since(start) >= 400*time.Millisecond)
}
Output:
true

func WithRelayGroup

func WithRelayGroup(groups ...*ConnGroup) RelayOption

WithRelayGroup adds the relay to each group while it runs: the group's CloseMembers and Close end it as the end of Relay's context would, also while a RelayFlow.Wait blocks, which closing the relay's ends cannot do, and Relay returns ErrRelayGroupClosed, which also matches the cause given to CloseMembers. A relay started on a closed group ends at once.

func WithRelayHalfClose

func WithRelayHalfClose() RelayOption

WithRelayHalfClose makes Relay pass EOF on instead of ending the relay: when one direction reaches EOF, Relay shuts down the writing side of the other end with CloseWrite and keeps copying the opposite direction until it ends too. An end without CloseWrite support, such as a net.Pipe, is closed as without this option. Pair it with an idle timeout, for example TimeoutConn, so a peer that never finishes cannot hold the relay open.

func WithRelayIdleTimeout

func WithRelayIdleTimeout(d time.Duration) RelayOption

WithRelayIdleTimeout ends the relay once no data has passed in either direction for d, and Relay then returns ErrRelayIdle. Relay watches the data it copies, also where it splices, and leaves the ends' deadlines alone, so it works on ends without deadlines too; time spent in a RelayFlow.Wait does not count as idle. The idle timeout keeps the fast paths of a direction without RelayFlow hooks: splice, in pieces, and the ends' own WriteTo and ReadFrom, through a writer or reader that records the data. A non-positive d sets none.

type RelaySide

type RelaySide uint8

RelaySide names an end of a Relay: RelayA is its argument a, RelayB its argument b.

const (
	RelayA RelaySide = iota + 1
	RelayB
)

The ends of a Relay.

func (RelaySide) Other

func (s RelaySide) Other() RelaySide

Other returns the other end.

func (RelaySide) String

func (s RelaySide) String() string

String returns "a" or "b".

type Scope

type Scope uint8

Scope is the reachability class of an IP address, as the IANA IPv4 and IPv6 Special-Purpose Address Registries (RFC 6890 and its updates) and the address architectures (RFC 791, RFC 4291) assign it. ScopeOf returns it.

const (
	// ScopeInvalid is the scope of the zero netip.Addr.
	ScopeInvalid Scope = iota
	// ScopeUnspecified is 0.0.0.0 and ::, which name no host but reach the
	// local host on many systems when dialed.
	ScopeUnspecified
	// ScopeLoopback is 127.0.0.0/8 and ::1.
	ScopeLoopback
	// ScopeLinkLocal is 169.254.0.0/16 and fe80::/10.
	ScopeLinkLocal
	// ScopePrivate is the space of private networks: 10.0.0.0/8,
	// 172.16.0.0/12, 192.168.0.0/16 (RFC 1918), the unique local addresses
	// fc00::/7 (RFC 4193) and the local-use translation prefix
	// 64:ff9b:1::/48 (RFC 8215).
	ScopePrivate
	// ScopeShared is 100.64.0.0/10, the shared address space of carrier-grade
	// NAT (RFC 6598).
	ScopeShared
	// ScopeMulticast is 224.0.0.0/4 and ff00::/8, of any multicast scope.
	ScopeMulticast
	// ScopeBroadcast is the limited broadcast address 255.255.255.255.
	ScopeBroadcast
	// ScopeDocumentation is 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24
	// (RFC 5737), 2001:db8::/32 (RFC 3849) and 3fff::/20 (RFC 9637).
	ScopeDocumentation
	// ScopeBenchmarking is 198.18.0.0/15 (RFC 2544) and 2001:2::/48
	// (RFC 5180).
	ScopeBenchmarking
	// ScopeReserved is unicast space that is not globally reachable and
	// has none of the uses above: "this network" 0.0.0.0/8, the IETF
	// protocol assignments 192.0.0.0/24 and 2001::/23 apart from their
	// globally reachable entries, the former 6to4 relay anycast
	// 192.88.99.0/24 (RFC 7526), 240.0.0.0/4, the discard and dummy
	// prefixes 100::/64 and 100:0:0:1::/64, the deprecated ORCHID
	// 2001:10::/28, the segment routing SIDs 5f00::/16, IPv6 outside
	// 2000::/3 that no entry names (such as the deprecated site-local
	// fec0::/10 and the IPv4-compatible ::/96), and translation addresses
	// that embed an IPv4 address that is not global (see ScopeOf).
	ScopeReserved
	// ScopeGlobal is globally reachable unicast.
	ScopeGlobal
)

Scopes, from the narrowest to the widest reach.

func ScopeOf

func ScopeOf(a netip.Addr) Scope

ScopeOf returns the scope of a, ignoring its zone. An IPv4-mapped IPv6 address has the scope of its IPv4 address.

The registries leave the reachability of 6to4 (2002::/16) and Teredo (2001::/32) addresses to the IPv4 addresses they embed, so such an address is ScopeGlobal when its embedded IPv4 addresses are (for Teredo, the server's and the client's) and ScopeReserved otherwise. The NAT64 well-known prefix 64:ff9b::/96 is globally reachable in the registry, and RFC 6052 forbids it to embed an IPv4 address that is not global, so its addresses are classified in the same way, which agrees with the registry for every valid one. The RFC 8215 local-use prefix 64:ff9b:1::/48 is ScopePrivate whatever it embeds.

Registry entries that are globally reachable inside larger reserved blocks, such as the PCP and TURN anycast addresses 192.0.0.9, 192.0.0.10, 2001:1::1 and 2001:1::2, are ScopeGlobal. Multicast addresses are ScopeMulticast whatever their multicast scope. ScopeOf does not allocate.

Example

Classify addresses before offering them to peers on the Internet.

package main

import (
	"fmt"
	"net/netip"

	"github.com/djylb/netx"
)

func main() {
	for _, s := range []string{"203.0.113.7", "100.72.1.2", "::ffff:192.168.1.10", "2002:808:808::1", "2606:4700::1111"} {
		a := netip.MustParseAddr(s)
		fmt.Println(s, netx.ScopeOf(a), netx.IsGlobal(a))
	}
}
Output:
203.0.113.7 documentation false
100.72.1.2 shared false
::ffff:192.168.1.10 private false
2002:808:808::1 global true
2606:4700::1111 global true

func (Scope) String

func (s Scope) String() string

String returns the name of s, such as "private", or "scope(N)" for a value that is not one of the constants.

type SingleConnListener

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

SingleConnListener is the listener that NewSingleConnListener returns. The zero value has no connection: its Accept blocks until Close.

func NewSingleConnListener

func NewSingleConnListener(c net.Conn) *SingleConnListener

NewSingleConnListener returns a listener whose first Accept returns c. Later Accept calls block until that connection or the listener is closed and then return net.ErrClosed, so a server loop such as http.Server.Serve handles c and returns when it is done.

Accept returns c wrapped so that its Close can be observed; InnermostConn unwraps it. The wrapper hides c's concrete type, so to serve TLS pass the plain connection and wrap the listener with tls.NewListener.

The connection belongs to the server once Accept has returned it: Close closes c only if Accept has not returned it yet, and otherwise only ends a blocked Accept, so closing the listener does not cut off the connection being served. To stop serving it, close the connection, or shut the server down, as http.Server.Shutdown does for its connections; Serve returns once the connection is closed.

Example

Run an http.Server on one connection; Serve returns once it is closed.

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"

	"github.com/djylb/netx"
)

func main() {
	client, server := net.Pipe()
	served := make(chan error, 1)
	go func() {
		served <- http.Serve(netx.NewSingleConnListener(server), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			_, _ = fmt.Fprint(w, "ok")
		}))
	}()

	req, _ := http.NewRequest(http.MethodGet, "http://single/", nil)
	req.Close = true // the server closes the connection after the response
	go func() { _ = req.Write(client) }()
	resp, err := http.ReadResponse(bufio.NewReader(client), req)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = resp.Body.Close() }()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
	fmt.Println(errors.Is(<-served, net.ErrClosed))
}
Output:
ok
true
Example (Shutdown)

Serve one connection with an http.Server and stop it from outside: closing the listener would leave the connection being served alone, so Shutdown, which closes the server's connections once idle, or Close ends it.

package main

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/http"
	"time"

	"github.com/djylb/netx"
)

func main() {
	client, server := net.Pipe()
	defer func() { _ = client.Close() }()
	srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})}
	served := make(chan error, 1)
	go func() { served <- srv.Serve(netx.NewSingleConnListener(server)) }()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_ = srv.Shutdown(ctx)
	fmt.Println(errors.Is(<-served, http.ErrServerClosed))
}
Output:
true

func (*SingleConnListener) Accept

func (l *SingleConnListener) Accept() (net.Conn, error)

Accept returns the connection the first time and then blocks until it or l is closed, returning net.ErrClosed.

func (*SingleConnListener) Addr

func (l *SingleConnListener) Addr() net.Addr

Addr returns the connection's LocalAddr, or "pipe" if it has none.

func (*SingleConnListener) Close

func (l *SingleConnListener) Close() error

Close ends a blocked Accept and closes the connection if Accept has not returned it yet.

type TimeoutConn

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

TimeoutConn closes an idle connection: before each read or write it moves the deadline of both directions to now plus the idle timeout. Construct it with NewTimeoutConn; SetIdleTimeout changes the timeout later, such as from a short one for a handshake to a longer one once it is done. A non-positive idle timeout sets none.

To keep the per-call cost to an atomic load, a read or write moves the deadline only once less than the idle timeout is left, and then to now plus the idle timeout and a small slack (idle/16, at most one second). A connection therefore never times out before it has been idle for the idle timeout, and at most that slack later.

SetDeadline, SetReadDeadline and SetWriteDeadline are remembered until they are changed again. Setting them and every read and write keep each direction's deadline at the earlier of the remembered one and now plus the idle timeout, so a deadline set to interrupt a blocked Read or Write stays in effect while the other direction is in use, and a later or zero one does not lift the idle timeout of a Read or Write that is already blocked. A zero time leaves only the idle timeout.

func NewTimeoutConn

func NewTimeoutConn(c net.Conn, idle time.Duration) *TimeoutConn

NewTimeoutConn wraps c and refreshes its deadline before each read or write, so that it times out after idle without either; a non-positive idle sets no idle timeout.

func (*TimeoutConn) Close

func (c *TimeoutConn) Close() error

Close implements net.Conn.

func (*TimeoutConn) CloseWrite

func (c *TimeoutConn) CloseWrite() error

CloseWrite shuts down the writing side of the wrapped connection, so the peer reads EOF while reads continue. It returns an error matching errors.ErrUnsupported when the wrapped connection cannot do that.

func (*TimeoutConn) IdleTimeout

func (c *TimeoutConn) IdleTimeout() time.Duration

IdleTimeout returns the idle timeout; see SetIdleTimeout.

func (*TimeoutConn) LocalAddr

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

LocalAddr implements net.Conn.

func (*TimeoutConn) NetConn

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

NetConn returns the connection that c wraps, as *tls.Conn's NetConn does; see InnermostConn and ConnAs. Its reads and writes do not refresh the idle timeout.

func (*TimeoutConn) NetxOwned

func (c *TimeoutConn) NetxOwned() OwnedLayers

NetxOwned describes the children closed with this layer.

func (*TimeoutConn) Read

func (c *TimeoutConn) Read(b []byte) (int, error)

func (*TimeoutConn) RemoteAddr

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

RemoteAddr implements net.Conn.

func (*TimeoutConn) SetDeadline

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

SetDeadline implements net.Conn.

func (*TimeoutConn) SetIdleTimeout

func (c *TimeoutConn) SetIdleTimeout(d time.Duration) error

SetIdleTimeout changes the idle timeout, also of a Read or Write already blocked; a non-positive d removes it, leaving the deadlines that were set.

func (*TimeoutConn) SetReadDeadline

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

SetReadDeadline implements net.Conn.

func (*TimeoutConn) SetWriteDeadline

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

SetWriteDeadline implements net.Conn.

func (*TimeoutConn) Write

func (c *TimeoutConn) Write(b []byte) (int, error)

type WrapOption

type WrapOption func(*wrapOptions)

WrapOption configures WrapConn.

func WithWrapParentClose

func WithWrapParentClose() WrapOption

WithWrapParentClose makes WrapConn close parent after closing rwc. parent is skipped when rwc already owns it, and net.ErrClosed from parent is ignored because rwc may already have closed it.

Directories

Path Synopsis
Package duplex joins a read half and a write half into a net.Conn, and lets either half be replaced while the connection is in use.
Package duplex joins a read half and a write half into a net.Conn, and lets either half be replaced while the connection is in use.
Package forwarded finds the address of the client of an HTTP request that came through proxies, from the X-Forwarded-For, X-Real-IP or Forwarded (RFC 7239) header fields that the proxies add, and formats those fields for a proxy to pass on.
Package forwarded finds the address of the client of an HTTP request that came through proxies, from the X-Forwarded-For, X-Real-IP or Forwarded (RFC 7239) header fields that the proxies add, and formats those fields for a proxy to pass on.
Package httphead reads and parses the heads of HTTP/1.x messages, the start line and the header fields, strictly where a lax reading lets two parties read one message in two ways, as in request smuggling, and leniently where that is safe (RFC 9110, RFC 9112).
Package httphead reads and parses the heads of HTTP/1.x messages, the start line and the header fields, strictly where a lax reading lets two parties read one message in two ways, as in request smuggling, and leniently where that is safe (RFC 9110, RFC 9112).
Package httpproxy implements an HTTP proxy server: CONNECT tunnels and forwarding of absolute-form requests such as "GET http://host/path", over any net.Conn, with optional Basic proxy authentication.
Package httpproxy implements an HTTP proxy server: CONNECT tunnels and forwarding of absolute-form requests such as "GET http://host/path", over any net.Conn, with optional Basic proxy authentication.
Package httprewrite rewrites the header fields of HTTP requests and responses with templates, for reverse proxies and servers: templates such as "${scheme}://${host}${request_uri}" in the style of the variables of common reverse proxies are compiled once and expanded per request, rule lists set, add and delete request and response fields, and redirects in Location and Refresh are rewritten from the backend's address to the public one.
Package httprewrite rewrites the header fields of HTTP requests and responses with templates, for reverse proxies and servers: templates such as "${scheme}://${host}${request_uri}" in the style of the variables of common reverse proxies are compiled once and expanded per request, rule lists set, add and delete request and response fields, and redirects in Location and Refresh are rewritten from the backend's address to the public one.
internal
bufpool
Package bufpool holds buffers shared by networking helpers.
Package bufpool holds buffers shared by networking helpers.
clock
Package clock provides clocks, timers and timing helpers for network I/O.
Package clock provides clocks, timers and timing helpers for network I/O.
creds
Package creds checks user names and passwords against a fixed account list for the servers of this module.
Package creds checks user names and passwords against a fixed account list for the servers of this module.
dgram
Package dgram provides bounded queues for datagram connections.
Package dgram provides bounded queues for datagram connections.
dnslookup
Package dnslookup resolves names and queues datagrams pending resolution.
Package dnslookup resolves names and queues datagrams pending resolution.
flowtable
Package flowtable manages datagram flow registration, acceptance and expiry.
Package flowtable manages datagram flow registration, acceptance and expiry.
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.
nettest
Package nettest holds helpers shared by the tests of netx packages.
Package nettest holds helpers shared by the tests of netx packages.
netutil
Package netutil holds the small helpers that the packages of this module share: address normalisation, the splice decision, the ContextDialer interface and the A-labels of internationalised names.
Package netutil holds the small helpers that the packages of this module share: address normalisation, the splice decision, the ContextDialer interface and the A-labels of internationalised names.
serve
Package serve holds the lifecycle that the servers of this module share: the listeners and connections they serve, a context that Close cancels, Shutdown and Close.
Package serve holds the lifecycle that the servers of this module share: the listeners and connections they serve, a context that Close cancels, Shutdown and Close.
Package memnet is an in-process network for tests: stream listeners and connections that behave like TCP sockets (buffered in both directions, half-close, reset on SetLinger(0), deadlines), packet endpoints that deliver whole datagrams and drop them when full, a resolver, dials from a chosen source host, and fault injection per address and direction: delay, rate, loss and cut links, driven by an injectable clock and randomness source.
Package memnet is an in-process network for tests: stream listeners and connections that behave like TCP sockets (buffered in both directions, half-close, reset on SetLinger(0), deadlines), packet endpoints that deliver whole datagrams and drop them when full, a resolver, dials from a chosen source host, and fault injection per address and direction: delay, rate, loss and cut links, driven by an injectable clock and randomness source.
Package proxydial dials TCP connections through HTTP CONNECT, SOCKS5 and SOCKS4 proxies, in the clear or over TLS.
Package proxydial dials TCP connections through HTTP CONNECT, SOCKS5 and SOCKS4 proxies, in the clear or over TLS.
Package proxyproto builds and decodes PROXY protocol v1 and v2 headers, which carry the original client and destination addresses of a proxied connection to the backend, and provides a Conn that reports those addresses for a connection whose peer sends one, with a Listener that wraps the connections it accepts.
Package proxyproto builds and decodes PROXY protocol v1 and v2 headers, which carry the original client and destination addresses of a proxied connection to the backend, and provides a Conn that reports those addresses for a connection whose peer sends one, with a Listener that wraps the connections it accepts.
Package safedial dials, and sends datagrams to, only the destinations that a policy allows, for a program that connects on behalf of a party it trusts less: a tunnel client that a server tells where to connect, a proxy, or a sender of webhooks to URLs that users give.
Package safedial dials, and sends datagrams to, only the destinations that a policy allows, for a program that connects on behalf of a party it trusts less: a tunnel client that a server tells where to connect, a proxy, or a sender of webhooks to URLs that users give.
Package socks5 implements SOCKS version 5 (RFC 1928) with username/password authentication (RFC 1929): a message codec for clients and servers, and a configurable Server.
Package socks5 implements SOCKS version 5 (RFC 1928) with username/password authentication (RFC 1929): a message codec for clients and servers, and a configurable Server.
Package tlsconn runs TLS handshakes over existing connections with a bound on how long they take, and provides a Dialer that layers TLS on any dialer, such as a proxy dialer.
Package tlsconn runs TLS handshakes over existing connections with a bound on how long they take, and provides a Dialer that layers TLS on any dialer, such as a proxy dialer.
Package transparent accepts TCP connections and UDP datagrams that a transparent proxy setup redirects to a local socket, and recovers the destination they were addressed to.
Package transparent accepts TCP connections and UDP datagrams that a transparent proxy setup redirects to a local socket, and recovers the destination they were addressed to.
Package udpflow turns UDP datagrams into connections that can be accepted from or dialed through a shared packet socket.
Package udpflow turns UDP datagrams into connections that can be accepted from or dialed through a shared packet socket.
Package wsconn implements the WebSocket protocol (RFC 6455) for tunnels, proxies and message channels: the opening handshake on both sides, a message API, and a net.Conn that carries a byte stream over binary messages.
Package wsconn implements the WebSocket protocol (RFC 6455) for tunnels, proxies and message channels: the opening handshake on both sides, a message API, and a net.Conn that carries a byte stream over binary messages.
wshttp
Package wshttp connects package wsconn to net/http: Upgrade and Serve turn the requests of a handler into WebSocket connections, Check and Accept do the same in two steps for a handler that decides on a request before anything is answered, and Dialer dials WebSocket over HTTP/2.
Package wshttp connects package wsconn to net/http: Upgrade and Serve turn the requests of a handler into WebSocket connections, Check and Accept do the same in two steps for a handler that decides on a request before anything is answered, and Dialer dials WebSocket over HTTP/2.

Jump to

Keyboard shortcuts

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