transport

package
v0.1.27 Latest Latest
Warning

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

Go to latest
Published: May 20, 2026 License: ISC Imports: 39 Imported by: 0

Documentation

Overview

Package transport provides pluggable transport implementations for WireGuard. Each transport wraps a base framing protocol (UDP, TCP, TLS, DTLS, WebSocket) with an optional proxy layer (none, TURN, SOCKS5, HTTP CONNECT) and exposes a unified conn.Bind to wireguard-go via MultiTransportBind.

Index

Constants

This section is empty.

Variables

View Source
var ErrBindAlreadyClosed = errors.New("transport: bind already closed")

ErrBindAlreadyClosed is returned when an operation is attempted on a closed MultiTransportBind.

View Source
var ErrTransportNotFound = errors.New("transport: not found")

ErrTransportNotFound is returned when a named transport cannot be located in the registry.

View Source
var ErrUDPNotSupported = errors.New("transport: proxy does not support UDP")

ErrUDPNotSupported is returned by ProxyDialer.DialPacket when the proxy does not support UDP tunnelling (e.g. HTTP CONNECT proxy).

View Source
var TurnCarrierDropsTotal atomic.Uint64

TurnCarrierDropsTotal lives outside the !lite build tag so the engine's metrics layer can reference it unconditionally. Lite builds never increment it (no TURN carriers exist there), so the gauge stays zero.

Functions

func BuildTLSServerConfigForServer

func BuildTLSServerConfigForServer(tlsCfg TLSConfig, certMgr *CertManager) (*tls.Config, error)

func DialTURNHTTPPacketConn

func DialTURNHTTPPacketConn(ctx context.Context, target string, useTLS bool, dialer ProxyDialer, certMgr *CertManager, tlsCfg TLSConfig, wsCfg WebSocketConfig) (net.PacketConn, error)

func DialTURNHTTPStreamConn

func DialTURNHTTPStreamConn(ctx context.Context, target string, useTLS bool, dialer ProxyDialer, certMgr *CertManager, tlsCfg TLSConfig, wsCfg WebSocketConfig) (net.Conn, error)

func DialTURNQUICPacketConn

func DialTURNQUICPacketConn(ctx context.Context, target string, dialer ProxyDialer, certMgr *CertManager, tlsCfg TLSConfig, wsCfg WebSocketConfig) (net.PacketConn, error)

func IsConnectionOriented

func IsConnectionOriented(cfg Config) bool

IsConnectionOriented reports whether a transport config describes a connection-oriented transport (TCP/TLS/DTLS/HTTP/HTTPS, or anything carried over a stream proxy such as SOCKS5 or HTTP CONNECT).

func ResolveDefaultTransportName

func ResolveDefaultTransportName(configs []Config, override string) string

ResolveDefaultTransportName picks the default transport name from a list of configs. If override is non-empty it is returned directly. Otherwise the first NCO transport is used; if none exist the first transport is used.

func TranslateFromIPv6

func TranslateFromIPv6(addr netip.Addr, prefix netip.Prefix) (netip.Addr, bool)

TranslateFromIPv6 extracts an IPv4 address from a NAT64 /96 prefix. Returns (addr, true) when addr falls within prefix, or (addr, false) when addr is not an IPv6 address in the given prefix.

func TranslateToIPv6

func TranslateToIPv6(addr netip.Addr, prefix netip.Prefix) netip.Addr

TranslateToIPv6 embeds an IPv4 address into a NAT64 /96 prefix. The IPv4 address occupies the last 32 bits of the 128-bit IPv6 address. prefix must be a /96; its host bits are ignored.

func ValidateBase

func ValidateBase(base string) error

ValidateBase checks that the Base field is one of the supported values.

func ValidateProxyType

func ValidateProxyType(t string) error

ValidateProxyType checks that the proxy Type field is valid.

func ValidateWebSocketUpgradeMode

func ValidateWebSocketUpgradeMode(mode string) error

Types

type BuildOptions

type BuildOptions struct {
	DirectDialerFactory func(cfg Config) (ProxyDialer, error)
}

type CertManager

type CertManager struct {
	CertFile       string
	KeyFile        string
	ReloadInterval time.Duration
	AutoGenerate   bool
	// contains filtered or unexported fields
}

CertManager manages a TLS certificate for server-mode transports. When CertFile and KeyFile are empty it auto-generates an ephemeral self-signed ECDSA P-256 certificate. When they are set it loads from disk and optionally reloads on a configured interval so that externally renewed certificates (e.g. from certbot) are picked up without a restart.

func NewCertManager

func NewCertManager(tlsCfg TLSConfig, autoGenerate bool) (*CertManager, error)

func (*CertManager) Close

func (m *CertManager) Close()

func (*CertManager) CurrentCertificate

func (m *CertManager) CurrentCertificate() (*tls.Certificate, error)

func (*CertManager) GetCertificate

func (m *CertManager) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate is suitable for use as tls.Config.GetCertificate.

func (*CertManager) GetClientCertificate

func (m *CertManager) GetClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Certificate, error)

GetClientCertificate is suitable for use as tls.Config.GetClientCertificate.

func (*CertManager) GetDTLSCertificate

func (m *CertManager) GetDTLSCertificate(_ *piondtls.ClientHelloInfo) (*tls.Certificate, error)

func (*CertManager) GetDTLSClientCertificate

func (m *CertManager) GetDTLSClientCertificate(_ *piondtls.CertificateRequestInfo) (*tls.Certificate, error)

func (*CertManager) Start

func (m *CertManager) Start() error

Start initialises the certificate. For auto-generated certs this happens once; for file-based certs the goroutine polls for renewal until ctx is cancelled.

func (*CertManager) TLSConfig

func (m *CertManager) TLSConfig() *tls.Config

TLSConfig returns a *tls.Config suitable for use as a server TLS config.

type Config

type Config struct {
	// Name is a unique identifier referenced by peers.
	Name string `yaml:"name" json:"name"`
	// Base is the framing protocol: udp | turn | tcp | tls | dtls | http |
	// https | quic | quic-ws | url
	Base string `yaml:"base" json:"base"`
	// Listen enables server-mode: the transport binds a fixed port and
	// accepts incoming WireGuard connections.
	Listen bool `yaml:"listen" json:"listen"`
	// ListenPort overrides the wireguard.listen_port for this transport.
	// Zero means inherit from wireguard.listen_port.
	ListenPort *int `yaml:"listen_port,omitempty" json:"listen_port,omitempty"`
	// ListenAddresses restricts the listen socket to specific IPs.
	// Empty means all interfaces.
	ListenAddresses []string `yaml:"listen_addresses,omitempty" json:"listen_addresses,omitempty"`

	// TLS holds TLS / DTLS / HTTPS / QUIC certificate and validation options.
	TLS TLSConfig `yaml:"tls,omitempty" json:"tls,omitempty"`
	// TURN configures TURN as the base transport. Set base: turn alongside
	// this block.
	TURN TURNConfig `yaml:"turn,omitempty" json:"turn,omitempty"`
	// URL is the full base URL for the "url" auto-negotiation transport,
	// e.g. "https://example.com/wg". Only used when Base = "url".
	URL string `yaml:"url,omitempty" json:"url,omitempty"`
	// WebSocket configures HTTP path / Host header details for HTTP-based transports.
	WebSocket WebSocketConfig `yaml:"websocket,omitempty" json:"websocket,omitempty"`

	// Proxy configures an optional proxy layer beneath the base transport.
	Proxy ProxyConfig `yaml:"proxy,omitempty" json:"proxy,omitempty"`

	// IPv6Translate maps IPv4 addresses to IPv6 using NAT64/DNS64 prefix.
	IPv6Translate bool `yaml:"ipv6_translate,omitempty" json:"ipv6_translate,omitempty"`
	// IPv6Prefix is the NAT64 /96 prefix. Defaults to "64:ff9b::/96".
	IPv6Prefix string `yaml:"ipv6_prefix,omitempty" json:"ipv6_prefix,omitempty"`
}

Config describes one pluggable transport entry from the YAML config.

func NormalizeConfig

func NormalizeConfig(cfg Config) Config

NormalizeConfig is a placeholder for any future transport-config normalization. Today it returns the config unchanged.

type ConfigError

type ConfigError struct {
	Field string
	Value string
	Msg   string
}

ConfigError is returned when a transport configuration field is invalid.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type ConnEstablishedEndpoint

type ConnEstablishedEndpoint struct {
	TransportID string
	// contains filtered or unexported fields
}

ConnEstablishedEndpoint is a live connection-oriented session. It is created at runtime when a connection is established and is discarded when the connection dies.

func NewConnEstablishedEndpoint

func NewConnEstablishedEndpoint(transportName, remoteAddr string, sess Session, peerIdent []byte) *ConnEstablishedEndpoint

NewConnEstablishedEndpoint creates an endpoint wrapping an active session. peerIdent must equal the IdentBytes() of the corresponding DialEndpoint so that WireGuard associates inbound and outbound packets correctly.

func (*ConnEstablishedEndpoint) ClearSrc

func (e *ConnEstablishedEndpoint) ClearSrc()

func (*ConnEstablishedEndpoint) DstIP

func (e *ConnEstablishedEndpoint) DstIP() netip.Addr

func (*ConnEstablishedEndpoint) DstToBytes

func (e *ConnEstablishedEndpoint) DstToBytes() []byte

func (*ConnEstablishedEndpoint) DstToString

func (e *ConnEstablishedEndpoint) DstToString() string

func (*ConnEstablishedEndpoint) IdentBytes

func (e *ConnEstablishedEndpoint) IdentBytes() []byte

func (*ConnEstablishedEndpoint) Kind

func (*ConnEstablishedEndpoint) Session

func (e *ConnEstablishedEndpoint) Session() Session

func (*ConnEstablishedEndpoint) SrcIP

func (e *ConnEstablishedEndpoint) SrcIP() netip.Addr

func (*ConnEstablishedEndpoint) SrcToString

func (e *ConnEstablishedEndpoint) SrcToString() string

func (*ConnEstablishedEndpoint) TransportName

func (e *ConnEstablishedEndpoint) TransportName() string

type DTLSTransport

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

DTLSTransport is a connection-oriented transport that carries WireGuard packets over DTLS. Unlike TCP/TLS there is no length prefix because DTLS is record-oriented (one WireGuard packet = one DTLS record).

Primary use case: making WireGuard traffic resemble WebRTC DTLS flows to bypass deep packet inspection firewalls, while retaining lower latency than TCP-based transports.

func NewDTLSTransport

func NewDTLSTransport(name string, dialer ProxyDialer, listenAddrs []string, certMgr *CertManager, tlsCfg TLSConfig) *DTLSTransport

NewDTLSTransport creates a DTLSTransport.

func (*DTLSTransport) Dial

func (t *DTLSTransport) Dial(ctx context.Context, target string) (Session, error)

Dial opens a client-mode DTLS session to target.

func (*DTLSTransport) IsConnectionOriented

func (t *DTLSTransport) IsConnectionOriented() bool

func (*DTLSTransport) Listen

func (t *DTLSTransport) Listen(_ context.Context, port int) (Listener, error)

Listen starts a DTLS server listener.

func (*DTLSTransport) Name

func (t *DTLSTransport) Name() string

type DialEndpoint

type DialEndpoint struct {
	Target      string // host:port (may be a hostname)
	TransportID string
	// contains filtered or unexported fields
}

DialEndpoint is a static configuration endpoint that represents "dial here when a packet must be sent". MultiTransportBind sees this endpoint type and dials the transport before forwarding the packet, producing a ConnEstablishedEndpoint for subsequent sends.

func NewDialEndpoint

func NewDialEndpoint(transportName, target string) *DialEndpoint

NewDialEndpoint creates a dial endpoint for a connection-oriented transport.

func (*DialEndpoint) ClearSrc

func (e *DialEndpoint) ClearSrc()

func (*DialEndpoint) DstIP

func (e *DialEndpoint) DstIP() netip.Addr

func (*DialEndpoint) DstToBytes

func (e *DialEndpoint) DstToBytes() []byte

func (*DialEndpoint) DstToString

func (e *DialEndpoint) DstToString() string

func (*DialEndpoint) IdentBytes

func (e *DialEndpoint) IdentBytes() []byte

func (*DialEndpoint) Kind

func (e *DialEndpoint) Kind() EndpointKind

func (*DialEndpoint) SrcIP

func (e *DialEndpoint) SrcIP() netip.Addr

func (*DialEndpoint) SrcToString

func (e *DialEndpoint) SrcToString() string

func (*DialEndpoint) TransportName

func (e *DialEndpoint) TransportName() string

type DirectDialer

type DirectDialer struct {
	// IPv6Translate enables NAT64/DNS64 address translation.
	IPv6Translate bool
	// IPv6Prefix is the NAT64 prefix.  Must be a /96.
	// Defaults to the well-known prefix 64:ff9b::/96.
	IPv6Prefix netip.Prefix
	// LocalIPv4 and LocalIPv6 pin direct sockets to a specific pre-TUN source
	// address so host-TUN full routes do not recurse back into the tunnel.
	LocalIPv4 netip.Addr
	LocalIPv6 netip.Addr
	// LookupNetIP overrides hostname resolution for outer transport dials.
	LookupNetIP func(ctx context.Context, network, host string) ([]netip.Addr, error)
}

DirectDialer is a ProxyDialer that dials directly through the host network with no proxy. Optional IPv6 translation maps IPv4 target addresses to a NAT64 /96 prefix before dialling.

func NewDirectDialer

func NewDirectDialer(ipv6Translate bool, prefix netip.Prefix) *DirectDialer

NewDirectDialer creates a DirectDialer. If ipv6Translate is true and prefix is the zero value the well-known prefix 64:ff9b::/96 is used.

func NewDirectDialerWithLocalAddrs

func NewDirectDialerWithLocalAddrs(ipv6Translate bool, prefix netip.Prefix, localIPv4, localIPv6 netip.Addr) *DirectDialer

func (*DirectDialer) DialContext

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

DialContext dials network+addr directly. When IPv6Translate is set, any IPv4 literal address is rewritten to its NAT64 representation before dialling.

func (*DirectDialer) DialPacket

func (d *DirectDialer) DialPacket(ctx context.Context, remoteHint string) (net.PacketConn, string, error)

DialPacket opens a UDP PacketConn for not-connection-oriented UDP traffic. remoteHint is translated when IPv6Translate is set.

func (*DirectDialer) SupportsHostname

func (d *DirectDialer) SupportsHostname() bool

SupportsHostname returns true; direct dialling resolves via the OS resolver.

type EndpointKind

type EndpointKind uint8

EndpointKind enumerates the three logical endpoint types.

const (
	// KindNotConnOriented is a not-connection-oriented endpoint (UDP, TURN).
	// Packets can be sent at any time without prior connection setup.
	KindNotConnOriented EndpointKind = iota
	// KindDial is a static configuration endpoint.  It does not support
	// direct packet sends; MultiTransportBind dials a real connection and
	// promotes it to KindConnEstablished when a packet must be sent.
	KindDial
	// KindConnEstablished is a live connection-oriented session.  It is a
	// transient runtime object and is never persisted across restarts.
	KindConnEstablished
)

type EndpointResetFunc

type EndpointResetFunc func(identBytes []byte, fallbackEndpoint string)

EndpointResetFunc is called by MultiTransportBind when a connection- oriented session dies and the effective endpoint for a peer needs to be reset. The engine uses this to update the WireGuard IPC state.

type HTTPConnectDialer

type HTTPConnectDialer struct {
	// Server is the proxy host:port.
	Server string
	// HTTPS wraps the connection to the proxy in TLS.
	HTTPS bool
	// Username and Password for Proxy-Authorization.
	Username, Password string
	// TLS configures HTTPS proxy TLS behavior.
	TLS TLSConfig
	// contains filtered or unexported fields
}

HTTPConnectDialer implements ProxyDialer by issuing HTTP CONNECT requests. It only supports TCP streams; UDP (DialPacket) returns ErrUDPNotSupported.

Certificate validation behaviour when reaching the proxy over HTTPS:

  • If no credentials are set: skip server verification by default.
  • If credentials are set: verify the proxy certificate by default.
  • tls.verify_peer overrides both defaults when explicitly configured.

func NewHTTPConnectDialer

func NewHTTPConnectDialer(server, scheme, username, password string, tlsCfg TLSConfig) (*HTTPConnectDialer, error)

NewHTTPConnectDialer creates an HTTPConnectDialer. scheme should be "http" or "https"; the HTTPS flag is set automatically.

func (*HTTPConnectDialer) DialContext

func (d *HTTPConnectDialer) DialContext(ctx context.Context, _, addr string) (net.Conn, error)

DialContext connects to addr via HTTP CONNECT through the proxy.

func (*HTTPConnectDialer) DialPacket

DialPacket is not supported by HTTP CONNECT proxies.

func (*HTTPConnectDialer) SupportsHostname

func (d *HTTPConnectDialer) SupportsHostname() bool

SupportsHostname returns true; HTTP CONNECT forwards the hostname verbatim.

type HTTPProxyConfig

type HTTPProxyConfig struct {
	// Server is the HTTP CONNECT proxy host:port.
	Server string `yaml:"server" json:"server"`
	// Username for HTTP Basic auth on the proxy. Empty means none.
	Username string `yaml:"username,omitempty" json:"username,omitempty"`
	// Password for HTTP Basic auth on the proxy.
	Password string `yaml:"password,omitempty" json:"password,omitempty"`
	// TLS configures HTTPS proxy transport.
	// When verify_peer is omitted, HTTPS proxies default to:
	// false for anonymous proxies, true when credentials are configured.
	TLS TLSConfig `yaml:"tls,omitempty" json:"tls,omitempty"`
}

HTTPProxyConfig configures an HTTP CONNECT proxy.

type HTTPUpgradeMode

type HTTPUpgradeMode string
const (
	HTTPUpgradeModeWebSocket  HTTPUpgradeMode = "websocket"
	HTTPUpgradeModeProxyGuard HTTPUpgradeMode = "proxyguard"
)

type Listener

type Listener interface {
	// Accept blocks until a new session arrives or ctx is cancelled.
	Accept(ctx context.Context) (Session, error)

	// Addr returns the local address the listener is bound to.
	Addr() net.Addr

	// Close stops accepting new sessions and releases resources.
	Close() error
}

Listener accepts incoming sessions from remote peers.

type MultiTransportBind

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

MultiTransportBind implements conn.Bind by multiplexing across multiple named Transport instances. It manages:

  • Multiple simultaneous listen-mode transports
  • Per-peer session state for connection-oriented transports
  • Roaming: any inbound packet updates the peer's active endpoint
  • Idle timeout for connection-oriented sessions (30 s, unless keepalive)
  • Rate-limited reconnect on sudden connection loss

func BuildRegistry

func BuildRegistry(
	configs []Config,
	wgPubKey [32]byte,
	defaultListenPort int,
	peerLookup PeerLookup,
	onEndpointReset EndpointResetFunc,
	legacyUDP bool,
) (*MultiTransportBind, error)

BuildRegistry constructs a MultiTransportBind from a slice of Config entries. wgPubKey is the WireGuard public key of this instance, embedded in TURN usernames when IncludeWGPublicKey is set.

Backward-compatibility: if configs is empty and legacyUDP is true a single default UDP transport is added.

func BuildRegistryWithOptions

func BuildRegistryWithOptions(
	configs []Config,
	wgPubKey [32]byte,
	defaultListenPort int,
	peerLookup PeerLookup,
	onEndpointReset EndpointResetFunc,
	legacyUDP bool,
	opts BuildOptions,
) (*MultiTransportBind, error)

func NewMultiTransportBind

func NewMultiTransportBind(peerLookup PeerLookup, onEndpointReset EndpointResetFunc) *MultiTransportBind

NewMultiTransportBind creates a MultiTransportBind. peerLookup and onEndpointReset may be nil; features that require them will be silently skipped.

func (*MultiTransportBind) ActiveSessions

func (b *MultiTransportBind) ActiveSessions() int

ActiveSessions returns the number of active connection-oriented sessions.

func (*MultiTransportBind) AddListenTransport

func (b *MultiTransportBind) AddListenTransport(t Transport)

AddListenTransport adds a transport that should be started in listen mode. Must be called before Open. The transport uses the port passed to Open.

func (*MultiTransportBind) AddListenTransportWithPort

func (b *MultiTransportBind) AddListenTransportWithPort(t Transport, port int)

AddListenTransportWithPort adds a transport in listen mode with a specific port override. When port != 0 it takes priority over the port passed to Open.

func (*MultiTransportBind) AddTransport

func (b *MultiTransportBind) AddTransport(t Transport)

AddTransport registers a transport. Must be called before Open.

func (*MultiTransportBind) BatchSize

func (b *MultiTransportBind) BatchSize() int

BatchSize implements conn.Bind.

func (*MultiTransportBind) Close

func (b *MultiTransportBind) Close() error

Close shuts down all listeners and sessions. Implements conn.Bind.

func (*MultiTransportBind) GetTransport

func (b *MultiTransportBind) GetTransport(name string) Transport

GetTransport returns the named transport or nil.

func (*MultiTransportBind) ListenPort

func (b *MultiTransportBind) ListenPort() uint16

ListenPort returns the port the first listen-mode transport is bound to, or 0 if no listeners are active.

func (*MultiTransportBind) Open

func (b *MultiTransportBind) Open(port uint16) ([]conn.ReceiveFunc, uint16, error)

Open starts all listen-mode transports and returns ReceiveFuncs for WireGuard. Implements conn.Bind.

func (*MultiTransportBind) ParseEndpoint

func (b *MultiTransportBind) ParseEndpoint(s string) (conn.Endpoint, error)

ParseEndpoint implements conn.Bind. Returns the appropriate endpoint type based on whether a transport name prefix is present.

func (*MultiTransportBind) ResetPeerSession

func (b *MultiTransportBind) ResetPeerSession(identBytes []byte)

ResetPeerSession closes any active session for the peer identified by identBytes and reverts its endpoint to the static configuration. Called by the engine's roam-fallback mechanism.

func (*MultiTransportBind) Send

func (b *MultiTransportBind) Send(bufs [][]byte, ep conn.Endpoint) error

Send transmits bufs to the given endpoint. Implements conn.Bind.

func (*MultiTransportBind) SessionSnapshots

func (b *MultiTransportBind) SessionSnapshots() []SessionSnapshot

SessionSnapshots returns a point-in-time view of the tracked transport sessions. The result is safe to use after the method returns.

func (*MultiTransportBind) SetDefaultTransport

func (b *MultiTransportBind) SetDefaultTransport(name string)

SetDefaultTransport sets the transport name used by ParseEndpoint when the endpoint string is a plain host:port (no transport prefix). Call this after BuildRegistry to guarantee deterministic fallback instead of map iteration.

func (*MultiTransportBind) SetMark

func (b *MultiTransportBind) SetMark(_ uint32) error

SetMark implements conn.Bind (no-op for userspace).

func (*MultiTransportBind) SetPeerSession

func (b *MultiTransportBind) SetPeerSession(identBytes []byte, ep conn.Endpoint, transport Transport, keepalive int)

SetPeerSession configures the static endpoint for a peer identified by identBytes. ep must be a NotConnOrientedEndpoint or DialEndpoint.

func (*MultiTransportBind) TransportNames

func (b *MultiTransportBind) TransportNames() []string

TransportNames returns the names of all registered transports.

type NotConnOrientedEndpoint

type NotConnOrientedEndpoint struct {
	AP          netip.AddrPort
	TransportID string
	// contains filtered or unexported fields
}

NotConnOrientedEndpoint represents a UDP or TURN relay endpoint. Packets are sent directly without establishing a persistent connection.

func NewNotConnOrientedEndpoint

func NewNotConnOrientedEndpoint(transportName string, ap netip.AddrPort) *NotConnOrientedEndpoint

NewNotConnOrientedEndpoint creates an endpoint for a not-connection- oriented transport such as UDP or TURN.

func (*NotConnOrientedEndpoint) ClearSrc

func (e *NotConnOrientedEndpoint) ClearSrc()

func (*NotConnOrientedEndpoint) DstIP

func (e *NotConnOrientedEndpoint) DstIP() netip.Addr

func (*NotConnOrientedEndpoint) DstToBytes

func (e *NotConnOrientedEndpoint) DstToBytes() []byte

func (*NotConnOrientedEndpoint) DstToString

func (e *NotConnOrientedEndpoint) DstToString() string

func (*NotConnOrientedEndpoint) IdentBytes

func (e *NotConnOrientedEndpoint) IdentBytes() []byte

func (*NotConnOrientedEndpoint) Kind

func (*NotConnOrientedEndpoint) SrcIP

func (e *NotConnOrientedEndpoint) SrcIP() netip.Addr

func (*NotConnOrientedEndpoint) SrcToString

func (e *NotConnOrientedEndpoint) SrcToString() string

func (*NotConnOrientedEndpoint) TransportName

func (e *NotConnOrientedEndpoint) TransportName() string

type OptionalString

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

OptionalString is a tri-state string used for config fields that must distinguish between: 1. not set, 2. explicitly null, 3. a concrete string value.

func NewOptionalString

func NewOptionalString(v string) OptionalString

NewOptionalString returns an OptionalString explicitly set to the given value. Use this when constructing config from code (tests, programmatic config builders); the YAML/JSON paths use the (un)marshallers below.

func (OptionalString) IsSet

func (o OptionalString) IsSet() bool

func (OptionalString) IsZero

func (o OptionalString) IsZero() bool

func (OptionalString) MarshalJSON

func (o OptionalString) MarshalJSON() ([]byte, error)

func (OptionalString) MarshalYAML

func (o OptionalString) MarshalYAML() (any, error)

func (*OptionalString) UnmarshalJSON

func (o *OptionalString) UnmarshalJSON(data []byte) error

func (*OptionalString) UnmarshalYAML

func (o *OptionalString) UnmarshalYAML(value *yaml.Node) error

func (OptionalString) Value

func (o OptionalString) Value() *string

type PeerInfo

type PeerInfo struct {
	// PersistentKeepalive is the configured keepalive interval in seconds.
	// Zero means none.
	PersistentKeepalive int
	// HasBufferedPackets reports whether WireGuard has data queued for this
	// peer that it is waiting to encrypt and send.
	HasBufferedPackets bool
}

PeerInfo contains transport-relevant runtime state for one WireGuard peer.

type PeerLookup

type PeerLookup func(identBytes []byte) PeerInfo

PeerLookup is a function the engine provides to MultiTransportBind so it can query per-peer state without importing the engine package.

type ProxyConfig

type ProxyConfig struct {
	// Type is: none | socks5 | http | https. Use base: turn for TURN.
	Type string `yaml:"type,omitempty" json:"type,omitempty"`

	// SOCKS5 settings, used when Type is "socks5".
	SOCKS5 SOCKS5ProxyConfig `yaml:"socks5,omitempty" json:"socks5,omitempty"`
	// HTTP CONNECT proxy settings, used when Type is "http" or "https".
	HTTP HTTPProxyConfig `yaml:"http,omitempty" json:"http,omitempty"`
}

ProxyConfig selects an optional proxy layer and its settings.

type ProxyDialer

type ProxyDialer interface {
	// DialContext dials a stream connection (TCP or TLS) to addr.
	DialContext(ctx context.Context, network, addr string) (net.Conn, error)

	// DialPacket returns a packet-oriented connection for UDP proxying via
	// SOCKS5 UDP ASSOCIATE.  remoteHint is the first destination address
	// (used when the SOCKS5 server needs it for the ASSOCIATE request).
	// Returns ErrUDPNotSupported when the proxy cannot carry UDP.
	DialPacket(ctx context.Context, remoteHint string) (net.PacketConn, string, error)

	// SupportsHostname reports whether the proxy can forward hostname targets
	// without the caller performing local DNS resolution.  When true,
	// hostnames from WireGuard peer Endpoint fields are passed verbatim.
	SupportsHostname() bool
}

ProxyDialer provides the underlying dialling mechanism used by a Transport. It abstracts over direct dialling, SOCKS5, and HTTP CONNECT proxies.

type QUICTransport

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

QUICTransport carries WireGuard packets over WebTransport datagrams on HTTP/3. This keeps the transport UDP-based while still looking like HTTPS.

func NewQUICTransport

func NewQUICTransport(name string, dialer ProxyDialer, listenAddrs []string, certMgr *CertManager, tlsCfg TLSConfig, path, hostHeader, connectHost string) *QUICTransport

func (*QUICTransport) Dial

func (t *QUICTransport) Dial(ctx context.Context, target string) (Session, error)

func (*QUICTransport) IsConnectionOriented

func (t *QUICTransport) IsConnectionOriented() bool

func (*QUICTransport) Listen

func (t *QUICTransport) Listen(_ context.Context, port int) (Listener, error)

func (*QUICTransport) Name

func (t *QUICTransport) Name() string

type QUICWebSocketTransport

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

QUICWebSocketTransport carries WireGuard packets as WebSocket binary frames over an HTTP/3 bidirectional stream (RFC 9220 — WebSocket over HTTP/3).

Unlike QUICTransport (which uses WebTransport datagrams), this transport runs WebSocket framing over the reliable HTTP/3 stream. This makes it compatible with reverse proxies (e.g. Cloudflare) that speak RFC 9220 on the QUIC side even when the origin serves plain HTTPS WebSocket.

Protocol:

Client → extended CONNECT :protocol=websocket over HTTP/3 stream
Both sides then exchange standard RFC 6455 binary frames on that stream.

func NewQUICWebSocketTransport

func NewQUICWebSocketTransport(
	name string,
	dialer ProxyDialer,
	listenAddrs []string,
	certMgr *CertManager,
	tlsCfg TLSConfig,
	path, hostHeader, connectHost string,
) *QUICWebSocketTransport

func (*QUICWebSocketTransport) Dial

func (t *QUICWebSocketTransport) Dial(ctx context.Context, target string) (Session, error)

Dial opens a RFC 9220 WebSocket-over-HTTP/3 session to target.

func (*QUICWebSocketTransport) IsConnectionOriented

func (t *QUICWebSocketTransport) IsConnectionOriented() bool

func (*QUICWebSocketTransport) Listen

func (t *QUICWebSocketTransport) Listen(_ context.Context, port int) (Listener, error)

Listen starts a QUIC HTTP/3 server that accepts RFC 9220 WebSocket upgrades.

func (*QUICWebSocketTransport) Name

func (t *QUICWebSocketTransport) Name() string

type SOCKS5Dialer

type SOCKS5Dialer struct {
	Server   string // host:port
	Username string
	Password string
}

SOCKS5Dialer implements ProxyDialer using a SOCKS5 proxy.

TCP connections use the standard CONNECT command. UDP tunnelling uses SOCKS5 UDP ASSOCIATE.

func NewSOCKS5Dialer

func NewSOCKS5Dialer(server, username, password string) (*SOCKS5Dialer, error)

NewSOCKS5Dialer creates a SOCKS5Dialer.

func (*SOCKS5Dialer) DialContext

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

DialContext connects to addr through the SOCKS5 proxy.

func (*SOCKS5Dialer) DialPacket

func (d *SOCKS5Dialer) DialPacket(ctx context.Context, remoteHint string) (net.PacketConn, string, error)

DialPacket opens a SOCKS5 UDP ASSOCIATE tunnel. It returns a PacketConn that wraps the SOCKS5 UDP relay, along with the relay address reported by the server (in host:port form).

func (*SOCKS5Dialer) SupportsHostname

func (d *SOCKS5Dialer) SupportsHostname() bool

SupportsHostname returns true; SOCKS5 can forward hostname targets.

type SOCKS5ProxyConfig

type SOCKS5ProxyConfig struct {
	// Server is the SOCKS5 proxy host:port.
	Server string `yaml:"server" json:"server"`
	// Username for SOCKS5 user/password auth (RFC 1929). Empty means none.
	Username string `yaml:"username,omitempty" json:"username,omitempty"`
	// Password for SOCKS5 user/password auth.
	Password string `yaml:"password,omitempty" json:"password,omitempty"`
}

SOCKS5ProxyConfig configures a SOCKS5 proxy.

type Session

type Session interface {
	// ReadPacket reads the next WireGuard packet payload.  The returned
	// slice is only valid until the next call to ReadPacket.
	// Returns io.EOF or net.ErrClosed when the session is done.
	ReadPacket() ([]byte, error)

	// WritePacket sends one WireGuard packet payload.
	WritePacket(pkt []byte) error

	// RemoteAddr returns a string representation of the peer address for
	// logging.
	RemoteAddr() string

	// Close tears down the session.  Idempotent.
	Close() error
}

Session is a single WireGuard packet exchange channel between two endpoints. For connection-oriented transports each peer has one Session; for not-connection-oriented transports (UDP, TURN) a single Session may be shared across all peers.

type SessionInfo

type SessionInfo struct {
	LocalAddr         string
	CarrierRemoteAddr string
	LogicalRemoteAddr string
}

SessionInfo exposes optional low-level socket details for status/debugging. Implementations may leave fields empty when the underlying transport does not expose them cleanly.

type SessionInfoProvider

type SessionInfoProvider interface {
	SessionInfo() SessionInfo
}

SessionInfoProvider is implemented by Session types that can report the local/remote OS-level addresses currently backing the transport session.

type SessionSnapshot

type SessionSnapshot struct {
	TransportName     string
	State             string
	StaticTarget      string
	CurrentTarget     string
	StaticEndpoint    string
	CurrentEndpoint   string
	LocalAddr         string
	CarrierRemoteAddr string
	LogicalRemoteAddr string
}

SessionSnapshot is a read-only runtime view of one tracked peer transport session, used by status APIs.

type TCPTransport

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

TCPTransport is a connection-oriented transport that carries WireGuard packets over a plain TCP stream. Each packet is prefixed with a 2-byte big-endian length field.

func NewTCPTransport

func NewTCPTransport(name string, dialer ProxyDialer, listenAddrs []string) *TCPTransport

NewTCPTransport creates a TCPTransport.

func (*TCPTransport) Dial

func (t *TCPTransport) Dial(ctx context.Context, target string) (Session, error)

Dial opens a client-mode TCP session to target.

func (*TCPTransport) IsConnectionOriented

func (t *TCPTransport) IsConnectionOriented() bool

func (*TCPTransport) Listen

func (t *TCPTransport) Listen(_ context.Context, port int) (Listener, error)

Listen binds a TCP listener.

func (*TCPTransport) Name

func (t *TCPTransport) Name() string

func (*TCPTransport) WithIdleTimeout added in v0.1.3

func (t *TCPTransport) WithIdleTimeout(d time.Duration) *TCPTransport

WithIdleTimeout returns a copy of the TCPTransport with a custom idle timeout. Zero disables idle detection. Primarily used in tests.

type TLSConfig

type TLSConfig struct {
	// CertFile path to PEM certificate. Empty → auto-generate self-signed.
	CertFile string `yaml:"cert_file,omitempty" json:"cert_file,omitempty"`
	// KeyFile path to PEM private key. Required when CertFile is set.
	KeyFile string `yaml:"key_file,omitempty" json:"key_file,omitempty"`
	// VerifyPeer enables remote certificate verification. Default false
	// because WireGuard already provides mutual authentication.
	VerifyPeer bool `yaml:"verify_peer,omitempty" json:"verify_peer,omitempty"`
	// ReloadInterval is how often the cert file is checked for renewal,
	// e.g. "60s". Empty or zero means no hot-reload.
	ReloadInterval string `yaml:"reload_interval,omitempty" json:"reload_interval,omitempty"`
	// CAFile path to PEM CA bundle used to validate the peer certificate.
	// For clients, empty means use the system roots. For servers that require
	// client certificates, a CAFile is mandatory.
	CAFile string `yaml:"ca_file,omitempty" json:"ca_file,omitempty"`
	// ServerSNI controls the client-side TLS Server Name Indication.
	// Unset means infer from the target hostname.
	// Explicit null means send no SNI at all.
	// A string value forces that SNI.
	ServerSNI OptionalString `yaml:"server_sni,omitempty" json:"server_sni,omitempty"`
	// contains filtered or unexported fields
}

TLSConfig holds certificate and validation settings for all TLS-based transports and proxies.

func (TLSConfig) MarshalJSON

func (c TLSConfig) MarshalJSON() ([]byte, error)

func (TLSConfig) MarshalYAML

func (c TLSConfig) MarshalYAML() (any, error)

func (*TLSConfig) UnmarshalJSON

func (c *TLSConfig) UnmarshalJSON(data []byte) error

func (*TLSConfig) UnmarshalYAML

func (c *TLSConfig) UnmarshalYAML(value *yaml.Node) error

type TLSTransport

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

TLSTransport is a connection-oriented transport that wraps the TCP 2-byte length-prefix framing in TLS. Server certificates are managed by CertManager (auto-generated or file-based with hot-reload).

func NewTLSTransport

func NewTLSTransport(name string, dialer ProxyDialer, listenAddrs []string, certMgr *CertManager, tlsCfg TLSConfig) *TLSTransport

NewTLSTransport creates a TLSTransport.

func (*TLSTransport) Dial

func (t *TLSTransport) Dial(ctx context.Context, target string) (Session, error)

Dial opens a client-mode TLS session to target.

func (*TLSTransport) IsConnectionOriented

func (t *TLSTransport) IsConnectionOriented() bool

func (*TLSTransport) Listen

func (t *TLSTransport) Listen(_ context.Context, port int) (Listener, error)

Listen binds a TLS listener.

func (*TLSTransport) Name

func (t *TLSTransport) Name() string

func (*TLSTransport) WithIdleTimeout added in v0.1.3

func (t *TLSTransport) WithIdleTimeout(d time.Duration) *TLSTransport

WithIdleTimeout returns a copy of the TLSTransport with a custom idle timeout. Zero disables idle detection. Primarily used in tests.

type TURNConfig

type TURNConfig struct {
	// Server is the TURN server URL or host:port.
	Server string `yaml:"server" json:"server"`
	// Username is the long-term TURN credential username.
	Username string `yaml:"username" json:"username"`
	// Password is the long-term TURN credential password.
	Password string `yaml:"password" json:"password"`
	// Realm is the TURN realm for long-term credentials.
	Realm string `yaml:"realm,omitempty" json:"realm,omitempty"`
	// Protocol is how to reach the TURN server: udp | tcp | tls | dtls | http | https | quic
	// Note: TURN does not need encryption for security, its only to bypass firewalls or hide the VPN as web traffic
	Protocol string `yaml:"protocol,omitempty" json:"protocol,omitempty"`
	// NoCreatePermission skips CreatePermission calls (open relays).
	NoCreatePermission bool `yaml:"no_create_permission,omitempty" json:"no_create_permission,omitempty"`
	// IncludeWGPublicKey appends the encrypted WireGuard public key to the
	// TURN username so the relay can associate allocations. The Wireguard public key is encrypted with the TURN password
	IncludeWGPublicKey bool `yaml:"include_wg_public_key,omitempty" json:"include_wg_public_key,omitempty"`
	// TLS configures TURN over TLS / DTLS. For TURN this is primarily useful
	// for obfuscation and optional client/server certificate filtering.
	TLS TLSConfig `yaml:"tls,omitempty" json:"tls,omitempty"`
	// Permissions is a list of IP/CIDR allowed to send relay traffic.
	Permissions []string `yaml:"permissions,omitempty" json:"permissions,omitempty"`
}

TURNConfig configures a TURN relay as the transport base.

type TURNHTTPServer

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

func NewTURNHTTPServer

func NewTURNHTTPServer(base net.Listener, path string) (*TURNHTTPServer, error)

func (*TURNHTTPServer) Addr

func (s *TURNHTTPServer) Addr() net.Addr

type TURNProxyConfig

type TURNProxyConfig = TURNConfig

TURNProxyConfig is an alias for TURNConfig used by some engine call sites.

type TURNQUICServer

type TURNQUICServer struct {
	PacketConn net.PacketConn
	// contains filtered or unexported fields
}

func ListenTURNQUICServer

func ListenTURNQUICServer(listenAddrs []string, port int, certMgr *CertManager, tlsCfg TLSConfig, path string) (*TURNQUICServer, error)

func (*TURNQUICServer) Addr

func (s *TURNQUICServer) Addr() net.Addr

func (*TURNQUICServer) Close

func (s *TURNQUICServer) Close() error

type TURNTransport

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

TURNTransport is a NOT-connection-oriented transport that relays WireGuard UDP packets through a TURN server. It supports TURN over UDP, TCP, TLS (TURNS), and DTLS.

TURN is not connection-oriented because it can multiplex multiple WireGuard flows over the same allocation. However, the underlying carrier (TCP, TLS, DTLS) may be replaced when it fails, triggering a full TURN reconnect.

func NewTURNTransport

func NewTURNTransport(name string, cfg TURNConfig, wsCfg WebSocketConfig, dialer ProxyDialer, wgPubKey [32]byte) (*TURNTransport, error)

NewTURNTransport creates a TURNTransport from the given transport config.

func (*TURNTransport) Close

func (t *TURNTransport) Close()

Close tears down the TURN allocation and the carrier, and stops any in-flight reconnect goroutine.

func (*TURNTransport) Dial

func (t *TURNTransport) Dial(ctx context.Context, target string) (Session, error)

Dial returns a lightweight write-capable session that sends packets through the shared TURN allocation to the requested destination. Read traffic still arrives through Listen/Accept because TURN is not connection-oriented.

func (*TURNTransport) IsConnectionOriented

func (t *TURNTransport) IsConnectionOriented() bool

func (*TURNTransport) Listen

func (t *TURNTransport) Listen(ctx context.Context, _ int) (Listener, error)

Listen allocates a TURN relay and returns a TURNListener that can both send to specific addresses and receive from any address.

func (*TURNTransport) Name

func (t *TURNTransport) Name() string

func (*TURNTransport) NoCreatePermissionForTest

func (t *TURNTransport) NoCreatePermissionForTest() bool

NoCreatePermissionForTest exposes the TURN permission mode for package-external tests.

func (*TURNTransport) RelayAddr

func (t *TURNTransport) RelayAddr() string

RelayAddr returns the TURN relay address (host:port) or empty string when not yet allocated.

func (*TURNTransport) TransportInfo

func (t *TURNTransport) TransportInfo() TransportInfo

func (*TURNTransport) UpdatePermissions

func (t *TURNTransport) UpdatePermissions(ips []string)

UpdatePermissions updates the set of IPs that are allowed to send to this relay allocation. Calling this after Listen is safe from any goroutine.

func (*TURNTransport) WGPublicKeyForTest

func (t *TURNTransport) WGPublicKeyForTest() [32]byte

WGPublicKeyForTest exposes the embedded WireGuard public key for package-external tests.

type Transport

type Transport interface {
	// Name returns the unique human-readable identifier for this transport.
	Name() string

	// IsConnectionOriented reports true when a single underlying connection
	// is used per peer (TCP, TLS, DTLS, WebSocket, or anything tunnelled
	// through a stream proxy such as SOCKS5 or HTTP CONNECT).
	// UDP and TURN return false.
	IsConnectionOriented() bool

	// Dial opens a client-mode session to target.  target is host:port and
	// may be a hostname when the proxy supports hostname forwarding.
	Dial(ctx context.Context, target string) (Session, error)

	// Listen starts a server-mode listener on the given port.  port==0
	// means pick any free port.  The returned Listener yields incoming
	// sessions via Accept.
	Listen(ctx context.Context, port int) (Listener, error)
}

Transport is a named framing + optional-proxy combination that can carry WireGuard packets.

type TransportEndpoint

type TransportEndpoint interface {
	conn.Endpoint
	// Kind returns the type of this endpoint.
	Kind() EndpointKind
	// TransportName returns the name of the transport that owns this endpoint.
	TransportName() string
	// IdentBytes returns a stable byte slice that WireGuard uses to match
	// this endpoint to a peer across multiple Endpoint instances.  All three
	// endpoint kinds for the same logical peer return the same bytes.
	IdentBytes() []byte
}

TransportEndpoint extends conn.Endpoint with transport metadata.

func AsTransportEndpoint

func AsTransportEndpoint(ep conn.Endpoint) TransportEndpoint

AsTransportEndpoint attempts to cast ep to TransportEndpoint. Returns nil when ep is not a transport endpoint.

type TransportInfo

type TransportInfo struct {
	Connected         bool
	CarrierProtocol   string
	CarrierLocalAddr  string
	CarrierRemoteAddr string
	RelayAddr         string
}

TransportInfo is optional runtime state exported by a transport instance. It is mainly used for management/status APIs.

type TransportInfoProvider

type TransportInfoProvider interface {
	TransportInfo() TransportInfo
}

TransportInfoProvider is implemented by transports that can report shared runtime state, for example a TURN allocation.

type UDPTransport

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

UDPTransport is a not-connection-oriented transport that sends and receives WireGuard packets as raw UDP datagrams. It can operate in listen mode (fixed source port, accepts packets from any peer) or outbound-only mode (ephemeral source port per peer).

func NewUDPTransport

func NewUDPTransport(name string, listenAddrs []string, dialer *DirectDialer) *UDPTransport

NewUDPTransport creates a UDPTransport with the given name.

func (*UDPTransport) Dial

func (t *UDPTransport) Dial(ctx context.Context, target string) (Session, error)

Dial creates an outbound-only UDP session to the given target. A connected UDP socket is used so the OS assigns a stable ephemeral source port for this peer.

func (*UDPTransport) IsConnectionOriented

func (t *UDPTransport) IsConnectionOriented() bool

func (*UDPTransport) Listen

func (t *UDPTransport) Listen(_ context.Context, port int) (Listener, error)

Listen opens UDP listeners on the configured addresses and the given port. Returns a UDPListener that yields inbound packets as sessions.

func (*UDPTransport) Name

func (t *UDPTransport) Name() string

type URLTransport

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

URLTransport is a connection-oriented transport that auto-negotiates the best available protocol for a given URL, trying in order:

  1. QUIC WebTransport (HTTP/3 datagrams) — fastest, lowest overhead
  2. QUIC WebSocket (RFC 9220) — QUIC stream + WS framing
  3. HTTPS WebSocket (TLS + TCP) — broadest compatibility

For http:// URLs only plain WebSocket (TCP) is tried. In listen mode the URL transport serves HTTPS / HTTP WebSocket and, for HTTPS URLs, both QUIC WebTransport and QUIC WebSocket (RFC 9220) on the same HTTP/3 path and UDP port.

func NewURLTransport

func NewURLTransport(
	name string,
	rawURL string,
	dialer ProxyDialer,
	listenAddrs []string,
	certMgr *CertManager,
	tlsCfg TLSConfig,
	connectHost, hostHeader string,
	advertiseHTTP3 bool,
) (*URLTransport, error)

NewURLTransport creates a URLTransport from a base URL, e.g. "https://example.com/wg" or "http://example.com/wg".

  • dialer is used for all sub-transports (TCP / UDP packet conn)
  • connectHost overrides DNS + connect host (domain fronting outer)
  • hostHeader overrides HTTP :authority / Host (domain fronting inner)
  • TLS settings (SNI, cert verification, cert files) from tlsCfg

func (*URLTransport) Dial

func (t *URLTransport) Dial(ctx context.Context, target string) (Session, error)

Dial auto-negotiates the best protocol for target.

For HTTPS URLs the order is:

  1. QUIC WebTransport (fastest)
  2. QUIC WebSocket RFC 9220
  3. HTTPS WebSocket (most compatible)

For HTTP URLs only plain WebSocket is tried.

func (*URLTransport) IsConnectionOriented

func (t *URLTransport) IsConnectionOriented() bool

func (*URLTransport) Listen

func (t *URLTransport) Listen(ctx context.Context, port int) (Listener, error)

Listen starts listeners for all three protocols simultaneously on the same port so any client variant can connect.

For http:// URLs only WebSocket is served. For https:// URLs: QUIC WebTransport + QUIC WebSocket + TLS/TCP WebSocket are served together.

func (*URLTransport) Name

func (t *URLTransport) Name() string

type WebSocketConfig

type WebSocketConfig struct {
	// Path is the HTTP path used for the WebSocket upgrade. Defaults to "/".
	Path string `yaml:"path,omitempty" json:"path,omitempty"`
	// UpgradeMode selects the HTTP upgrade protocol used by client-mode
	// HTTP/HTTPS transports:
	//   "" | "websocket" → RFC 6455 WebSocket upgrade (default)
	//   "proxyguard"     → ProxyGuard UoTLV/1 native HTTP upgrade
	//
	// Listen mode always accepts both WebSocket and UoTLV/1 on the same path.
	UpgradeMode string `yaml:"upgrade_mode,omitempty" json:"upgrade_mode,omitempty"`
	// ConnectHost overrides the host used for DNS lookup and TCP/QUIC
	// connection. When empty the peer endpoint host is used. This is the
	// first of three independently configurable host values for domain
	// fronting:
	//   ConnectHost  → DNS + actual TCP/QUIC connect
	//   TLS.ServerSNI → TLS ClientHello SNI
	//   HostHeader   → HTTP Host / :authority header (inner, often encrypted)
	ConnectHost string `yaml:"connect_host,omitempty" json:"connect_host,omitempty"`
	// HostHeader overrides the HTTP Host / :authority header sent in the
	// upgrade request. Used for domain fronting where the HTTP layer is
	// encrypted and the CDN routes on the inner host. Empty means use the
	// target host.
	HostHeader string `yaml:"host_header,omitempty" json:"host_header,omitempty"`
	// AdvertiseHTTP3 adds Alt-Svc: h3 on HTTPS listener responses so clients
	// can discover a matching HTTP/3 endpoint on the same port. This does not
	// enable QUIC by itself; configure a real QUIC listener separately.
	AdvertiseHTTP3 bool `yaml:"advertise_http3,omitempty" json:"advertise_http3,omitempty"`
}

type WebSocketOption

type WebSocketOption func(*WebSocketTransport)

func WithWebSocketAdvertiseHTTP3

func WithWebSocketAdvertiseHTTP3(advertise bool) WebSocketOption

func WithWebSocketConnectHost

func WithWebSocketConnectHost(host string) WebSocketOption

func WithWebSocketHostHeader

func WithWebSocketHostHeader(host string) WebSocketOption

func WithWebSocketPath

func WithWebSocketPath(path string) WebSocketOption

func WithWebSocketUpgradeMode

func WithWebSocketUpgradeMode(mode HTTPUpgradeMode) WebSocketOption

type WebSocketTransport

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

WebSocketTransport is a connection-oriented transport that carries WireGuard packets over an HTTP upgrade.

It supports:

  • ws:// / wss:// WebSocket framing
  • ProxyGuard UoTLV/1 native HTTP upgrade with TCP-style 2-byte framing

In listen mode an embedded HTTP server is started that upgrades inbound connections; in client mode the configured HTTP upgrade protocol is used.

Certificate validation mirrors TLSTransport: disabled by default because WireGuard already authenticates peers, but can be enabled with verifyPeer.

func NewWebSocketTransport

func NewWebSocketTransport(name, scheme string, dialer ProxyDialer, listenAddrs []string, certMgr *CertManager, tlsCfg TLSConfig, opts ...WebSocketOption) *WebSocketTransport

NewWebSocketTransport creates a WebSocketTransport. scheme should be "http" (ws://) or "https" (wss://).

func (*WebSocketTransport) Dial

func (t *WebSocketTransport) Dial(ctx context.Context, target string) (Session, error)

Dial opens a client-mode WebSocket session to target (host:port). Domain fronting: connectHost sets the DNS/TCP connect address; TLS.ServerSNI sets the ClientHello SNI; HostHeader sets the HTTP Host (inner host).

func (*WebSocketTransport) IsConnectionOriented

func (t *WebSocketTransport) IsConnectionOriented() bool

func (*WebSocketTransport) Listen

func (t *WebSocketTransport) Listen(_ context.Context, port int) (Listener, error)

Listen starts a WebSocket server.

func (*WebSocketTransport) Name

func (t *WebSocketTransport) Name() string

func (*WebSocketTransport) WithIdleTimeout added in v0.1.3

func (t *WebSocketTransport) WithIdleTimeout(d time.Duration) *WebSocketTransport

WithIdleTimeout returns a copy of the WebSocketTransport with a custom idle timeout for ProxyGuard sessions. Zero disables idle detection. Primarily used in tests.

Jump to

Keyboard shortcuts

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