diff --git a/admission/admission.go b/admission/admission.go index 1503c2e3..4058a194 100644 --- a/admission/admission.go +++ b/admission/admission.go @@ -1,3 +1,20 @@ +// Package admission implements access control for incoming connections. +// Before a connection is handled, the admission controller checks whether +// the client's address is allowed to use the service. +// +// The package provides: +// - NewAdmission: a local admission controller backed by IP/CIDR matchers, +// with optional periodic reload from file, Redis, or HTTP sources. +// - AdmissionGroup: composes multiple admission controllers; all must +// admit for the connection to proceed. +// - Plugin-based admission (gRPC and HTTP) in the plugin sub-package. +// - Connection wrappers in the wrapper sub-package that enforce +// admission checks per-read (for TCP) and per-packet (for UDP). +// +// Matching modes: +// - Whitelist (whitelist=true): only addresses matching a rule are admitted. +// - Blacklist (whitelist=false): addresses matching a rule are denied; +// everything else is admitted. This is the default. package admission import ( @@ -16,71 +33,122 @@ import ( xlogger "github.com/go-gost/x/logger" ) +// options holds the configuration for a localAdmission instance. type options struct { - whitelist bool - matchers []string - fileLoader loader.Loader + // whitelist toggles between blacklist and whitelist mode. + // When false (default): matching addresses are denied. + // When true: only matching addresses are allowed. + whitelist bool + + // matchers holds static patterns provided at construction time + // (e.g. from config file or command-line arguments). + matchers []string + + // fileLoader loads patterns from a file or directory. + // Supports hot-reload via file watching if the loader implements Lister. + fileLoader loader.Loader + + // redisLoader loads patterns from a Redis set or key. + // Supports hot-reload via periodic polling if the loader implements Lister. redisLoader loader.Loader - httpLoader loader.Loader - period time.Duration - logger logger.Logger + + // httpLoader loads patterns from an HTTP endpoint. + // Supports hot-reload via periodic polling. + httpLoader loader.Loader + + // period controls the interval between automatic reloads. + // Values less than 1 second are clamped to 1 second. + // A value <= 0 disables periodic reload (load once at startup). + period time.Duration + + // logger is used for debug and warning messages. + // Falls back to a no-op logger if nil. + logger logger.Logger } +// Option is a functional option for configuring an admission controller. type Option func(opts *options) +// WhitelistOption sets whether the admission controller operates in +// whitelist mode. In whitelist mode, only addresses matching one or more +// rules are admitted; all others are denied. func WhitelistOption(whitelist bool) Option { return func(opts *options) { opts.whitelist = whitelist } } +// MatchersOption sets static match patterns that are combined with +// dynamically loaded patterns on each reload. Patterns may be: +// - Bare IP addresses: "192.168.1.1", "::1" +// - CIDR networks: "10.0.0.0/8", "fd00::/8" +// - Hostnames: resolved to IP addresses via DNS func MatchersOption(matchers []string) Option { return func(opts *options) { opts.matchers = matchers } } +// ReloadPeriodOption sets the interval for automatically reloading +// patterns from external loaders (file, Redis, HTTP). A value <= 0 +// disables periodic reloading. func ReloadPeriodOption(period time.Duration) Option { return func(opts *options) { opts.period = period } } +// FileLoaderOption sets the file-based pattern loader. func FileLoaderOption(fileLoader loader.Loader) Option { return func(opts *options) { opts.fileLoader = fileLoader } } +// RedisLoaderOption sets the Redis-based pattern loader. func RedisLoaderOption(redisLoader loader.Loader) Option { return func(opts *options) { opts.redisLoader = redisLoader } } +// HTTPLoaderOption sets the HTTP-based pattern loader. func HTTPLoaderOption(httpLoader loader.Loader) Option { return func(opts *options) { opts.httpLoader = httpLoader } } +// LoggerOption sets the logger for the admission controller. func LoggerOption(logger logger.Logger) Option { return func(opts *options) { opts.logger = logger } } +// localAdmission is the in-process admission controller. It maintains +// two matchers — one for individual IP addresses and one for CIDR +// networks — and checks incoming addresses against them. +// +// The matchers are rebuilt atomically on each reload: new patterns +// are loaded, parsed into IPs and CIDRs, and the matchers are swapped +// under a write lock. type localAdmission struct { - ipMatcher matcher.Matcher - cidrMatcher matcher.Matcher - mu sync.RWMutex + ipMatcher matcher.Matcher // matches individual IP addresses + cidrMatcher matcher.Matcher // matches CIDR network ranges + mu sync.RWMutex // protects ipMatcher and cidrMatcher cancelFunc context.CancelFunc options options logger logger.Logger } -// NewAdmission creates and initializes a new Admission using matcher patterns as its match rules. -// The rules will be reversed if the reverse is true. +// NewAdmission creates a local admission controller with the given options. +// It starts a background goroutine that periodically reloads patterns +// from configured external sources (file, Redis, HTTP). +// +// By default the controller operates in blacklist mode: any address +// matching the loaded patterns is denied. Use WhitelistOption(true) +// to invert this. func NewAdmission(opts ...Option) admission.Admission { var options options for _, opt := range opts { @@ -104,6 +172,17 @@ func NewAdmission(opts ...Option) admission.Admission { return p } +// Admit decides whether the given network address is allowed. +// It returns true if the address should be accepted, false otherwise. +// +// The address is first stripped of its port (if present), then matched +// against the IP and CIDR matchers. The whitelist/blacklist mode +// determines how the match result is interpreted: +// +// Blacklist (whitelist=false): admit if NOT matched +// Whitelist (whitelist=true): admit only if matched +// +// An empty address or a nil receiver always returns true. func (p *localAdmission) Admit(ctx context.Context, network, addr string, opts ...admission.Option) bool { if addr == "" || p == nil { return true @@ -125,6 +204,8 @@ func (p *localAdmission) Admit(ctx context.Context, network, addr string, opts . return b } +// periodReload triggers an immediate reload, then — if a positive period +// is configured — reloads on each tick. It exits when ctx is cancelled. func (p *localAdmission) periodReload(ctx context.Context) error { if err := p.reload(ctx); err != nil { p.logger.Warnf("reload: %v", err) @@ -152,6 +233,8 @@ func (p *localAdmission) periodReload(ctx context.Context) error { } } +// reload loads patterns from all configured sources, parses them into +// IP addresses and CIDR networks, and atomically swaps the matchers. func (p *localAdmission) reload(ctx context.Context) error { v, err := p.load(ctx) if err != nil { @@ -170,6 +253,7 @@ func (p *localAdmission) reload(ctx context.Context) error { inets = append(inets, inet) continue } + // Try DNS resolution as a last resort. if ipAddr, _ := net.ResolveIPAddr("ip", pattern); ipAddr != nil { p.logger.Debugf("resolve IP: %s -> %s", pattern, ipAddr) ips = append(ips, ipAddr.IP) @@ -185,6 +269,9 @@ func (p *localAdmission) reload(ctx context.Context) error { return nil } +// load collects patterns from all configured external loaders +// (file, Redis, HTTP). It prefers the Lister interface when available, +// falling back to loading raw content via Load and parsing line-by-line. func (p *localAdmission) load(ctx context.Context) (patterns []string, err error) { if p.options.fileLoader != nil { if lister, ok := p.options.fileLoader.(loader.Lister); ok { @@ -239,6 +326,8 @@ func (p *localAdmission) load(ctx context.Context) (patterns []string, err error return } +// parsePatterns reads a newline-delimited stream and returns a list of +// non-empty, trimmed lines after stripping comments. func (p *localAdmission) parsePatterns(r io.Reader) (patterns []string, err error) { if r == nil { return @@ -255,6 +344,9 @@ func (p *localAdmission) parsePatterns(r io.Reader) (patterns []string, err erro return } +// parseLine strips inline comments (everything after the first '#') +// and trims surrounding whitespace. It returns an empty string if +// the line was a comment-only or blank line. func (p *localAdmission) parseLine(s string) string { if n := strings.IndexByte(s, '#'); n >= 0 { s = s[:n] @@ -262,6 +354,8 @@ func (p *localAdmission) parseLine(s string) string { return strings.TrimSpace(s) } +// matched returns true if addr is matched by either the IP or CIDR +// matcher. Caller must hold at least a read lock. func (p *localAdmission) matched(addr string) bool { p.mu.RLock() defer p.mu.RUnlock() @@ -270,6 +364,9 @@ func (p *localAdmission) matched(addr string) bool { p.cidrMatcher.Match(addr) } +// Close stops the background reload goroutine and closes all external +// loaders. It is safe to call after the admission controller is no +// longer needed. func (p *localAdmission) Close() error { p.cancelFunc() if p.options.fileLoader != nil { @@ -284,10 +381,18 @@ func (p *localAdmission) Close() error { return nil } +// admissionGroup composes multiple admission controllers into one. +// All controllers in the group must admit for the overall result to +// be true (logical AND). type admissionGroup struct { admissions []admission.Admission } +// AdmissionGroup creates a composite admission controller that requires +// every member to admit the address. If any member denies, the address +// is denied immediately (short-circuit evaluation). +// +// Nil members are skipped. func AdmissionGroup(admissions ...admission.Admission) admission.Admission { return &admissionGroup{ admissions: admissions, diff --git a/admission/plugin/grpc.go b/admission/plugin/grpc.go index 63a3f791..c843bc17 100644 --- a/admission/plugin/grpc.go +++ b/admission/plugin/grpc.go @@ -1,3 +1,9 @@ +// Package admission implements gRPC-based admission plugins. +// An admission plugin delegates the admit/deny decision to an external +// service via gRPC. This allows admission logic to be implemented in +// a separate process using any language supported by protobuf. +// +// The gRPC service definition is in plugin/admission/proto. package admission import ( @@ -11,13 +17,27 @@ import ( "google.golang.org/grpc" ) +// grpcPlugin is an admission controller that delegates to an external +// gRPC admission service. +// +// If the gRPC connection cannot be established at construction time, +// the client field remains nil and Admit returns true (fail-open), +// allowing all traffic through rather than blocking everything. type grpcPlugin struct { conn grpc.ClientConnInterface client proto.AdmissionClient log logger.Logger } -// NewGRPCPlugin creates an Admission plugin based on gRPC. +// NewGRPCPlugin creates an admission controller that communicates with +// an external gRPC admission service at the given address. +// +// The name is used only for log identification. The addr should be a +// gRPC target string (e.g. "127.0.0.1:9000"). Additional plugin options +// (TLS, token, retry) can be passed via opts. +// +// If the connection fails, the plugin logs the error and operates in +// fail-open mode: all admission requests return true. func NewGRPCPlugin(name string, addr string, opts ...plugin.Option) admission.Admission { var options plugin.Options for _, opt := range opts { @@ -43,6 +63,13 @@ func NewGRPCPlugin(name string, addr string, opts ...plugin.Option) admission.Ad return p } +// Admit sends an admission request to the external gRPC service. +// It passes the network, address, and service name from the client +// connection. +// +// If the gRPC client is nil (connection failed at startup), it returns +// true (fail-open). If the RPC returns an error, it logs the error and +// returns false. func (p *grpcPlugin) Admit(ctx context.Context, network, addr string, opts ...admission.Option) bool { if p.client == nil { return true @@ -66,6 +93,7 @@ func (p *grpcPlugin) Admit(ctx context.Context, network, addr string, opts ...ad return r.Ok } +// Close closes the underlying gRPC connection if it implements io.Closer. func (p *grpcPlugin) Close() error { if closer, ok := p.conn.(io.Closer); ok { return closer.Close() diff --git a/admission/plugin/http.go b/admission/plugin/http.go index f17b0542..39b806a0 100644 --- a/admission/plugin/http.go +++ b/admission/plugin/http.go @@ -11,16 +11,24 @@ import ( "github.com/go-gost/x/internal/plugin" ) +// httpPluginRequest is the JSON payload sent to the HTTP admission service. type httpPluginRequest struct { Service string `json:"service"` Network string `json:"network"` Addr string `json:"addr"` } +// httpPluginResponse is the JSON response expected from the HTTP +// admission service. OK indicates whether the address is admitted. type httpPluginResponse struct { OK bool `json:"ok"` } +// httpPlugin is an admission controller that delegates to an external +// HTTP admission service via JSON POST requests. +// +// The HTTP client is created via plugin.NewHTTPClient, which configures +// timeouts, TLS, and token-based authentication from plugin options. type httpPlugin struct { url string client *http.Client @@ -28,7 +36,14 @@ type httpPlugin struct { log logger.Logger } -// NewHTTPPlugin creates an Admission plugin based on HTTP. +// NewHTTPPlugin creates an admission controller that communicates with +// an external HTTP admission service at the given URL. +// +// The name is used only for log identification. On each Admit call, +// a JSON-encoded httpPluginRequest is POSTed to the URL. A 200 response +// with {"ok": true} admits the address; any other response denies it. +// +// If the HTTP client is nil, all admission requests return false. func NewHTTPPlugin(name string, url string, opts ...plugin.Option) admission.Admission { var options plugin.Options for _, opt := range opts { @@ -46,6 +61,16 @@ func NewHTTPPlugin(name string, url string, opts ...plugin.Option) admission.Adm } } +// Admit sends a JSON POST request to the configured HTTP endpoint. +// The request includes the service name, network, and client address. +// +// The address is admitted only if ALL of the following are true: +// - The HTTP client is non-nil +// - The request is successfully sent +// - The response has status 200 OK +// - The response body decodes as JSON with "ok": true +// +// Any error, non-200 status, or decode failure results in denial. func (p *httpPlugin) Admit(ctx context.Context, network, addr string, opts ...admission.Option) (ok bool) { if p.client == nil { return @@ -92,6 +117,8 @@ func (p *httpPlugin) Admit(ctx context.Context, network, addr string, opts ...ad return res.OK } +// Close closes idle connections in the HTTP client's connection pool. +// It does not shut down the client itself. func (p *httpPlugin) Close() error { if p.client != nil { p.client.CloseIdleConnections() diff --git a/admission/wrapper/conn.go b/admission/wrapper/conn.go index cc5515f6..b9097453 100644 --- a/admission/wrapper/conn.go +++ b/admission/wrapper/conn.go @@ -18,11 +18,22 @@ var ( errUnsupport = errors.New("unsupported operation") ) +// serverConn wraps a TCP connection (net.Conn) with per-read admission +// checking. Unlike the listener wrapper — which rejects at accept time — +// this wrapper re-validates the remote address on each Read call. +// This is useful when the admission rules may change during the lifetime +// of a connection, or when the connection was established before +// admission wrappers were applied. type serverConn struct { net.Conn admission admission.Admission } +// WrapConn wraps a net.Conn with per-read admission control. +// If admission is nil, the original connection is returned unchanged. +// +// When admission is denied on a Read, io.EOF is returned so the caller +// sees a clean end-of-stream rather than a hard error. func WrapConn(admission admission.Admission, c net.Conn) net.Conn { if admission == nil { return c @@ -33,6 +44,9 @@ func WrapConn(admission admission.Admission, c net.Conn) net.Conn { } } +// Read checks the remote address against the admission controller +// before delegating to the underlying connection. If denied, it returns +// io.EOF to signal end-of-stream. func (c *serverConn) Read(b []byte) (n int, err error) { if c.admission != nil && !c.admission.Admit(context.Background(), c.RemoteAddr().Network(), c.RemoteAddr().String()) { @@ -42,6 +56,9 @@ func (c *serverConn) Read(b []byte) (n int, err error) { return c.Conn.Read(b) } +// SyscallConn exposes the underlying raw connection for socket-level +// operations (e.g. setting SO_MARK, SO_REUSEPORT). Returns +// errUnsupport if the inner connection does not support this. func (c *serverConn) SyscallConn() (rc syscall.RawConn, err error) { if sc, ok := c.Conn.(syscall.Conn); ok { rc, err = sc.SyscallConn() @@ -51,6 +68,7 @@ func (c *serverConn) SyscallConn() (rc syscall.RawConn, err error) { return } +// CloseRead shuts down the read side of the connection if supported. func (c *serverConn) CloseRead() error { if sc, ok := c.Conn.(xio.CloseRead); ok { return sc.CloseRead() @@ -58,6 +76,7 @@ func (c *serverConn) CloseRead() error { return xio.ErrUnsupported } +// CloseWrite shuts down the write side of the connection if supported. func (c *serverConn) CloseWrite() error { if sc, ok := c.Conn.(xio.CloseWrite); ok { return sc.CloseWrite() @@ -65,6 +84,8 @@ func (c *serverConn) CloseWrite() error { return xio.ErrUnsupported } +// Context returns the context carried by the underlying connection, +// or nil if the connection does not carry context. func (c *serverConn) Context() context.Context { if innerCtx, ok := c.Conn.(ctx.Context); ok { return innerCtx.Context() @@ -72,11 +93,19 @@ func (c *serverConn) Context() context.Context { return nil } +// packetConn wraps a net.PacketConn with per-packet admission checking. +// Packets from denied addresses are silently dropped and the read +// loop continues to the next packet. type packetConn struct { net.PacketConn admission admission.Admission } +// WrapPacketConn wraps a net.PacketConn with per-packet admission control. +// If admission is nil, the original connection is returned unchanged. +// +// Denied packets are silently discarded; ReadFrom loops until it receives +// a packet from an allowed address or encounters an error. func WrapPacketConn(admission admission.Admission, pc net.PacketConn) net.PacketConn { if admission == nil { return pc @@ -87,6 +116,8 @@ func WrapPacketConn(admission admission.Admission, pc net.PacketConn) net.Packet } } +// ReadFrom reads the next packet from an admitted address. Packets from +// denied addresses are discarded and the method retries automatically. func (c *packetConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { for { n, addr, err = c.PacketConn.ReadFrom(p) @@ -103,6 +134,7 @@ func (c *packetConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { } } +// Context returns the context carried by the underlying packet connection. func (c *packetConn) Context() context.Context { if innerCtx, ok := c.PacketConn.(ctx.Context); ok { return innerCtx.Context() @@ -110,11 +142,21 @@ func (c *packetConn) Context() context.Context { return nil } +// udpConn wraps a packet connection as a UDP-specific connection. +// It provides the same admission filtering as packetConn, plus UDP- +// specific operations (ReadFromUDP, ReadMsgUDP, WriteToUDP, WriteMsgUDP, +// SetDSCP, etc.). +// +// The wrapper delegates to optional interfaces on the underlying +// connection, returning errUnsupport if the capability is not available. type udpConn struct { net.PacketConn admission admission.Admission } +// WrapUDPConn wraps a net.PacketConn as a udp.Conn with admission control. +// This is used in UDP forwarding paths where the connection is treated +// as a connected UDP socket. func WrapUDPConn(admission admission.Admission, pc net.PacketConn) udp.Conn { return &udpConn{ PacketConn: pc, @@ -122,6 +164,9 @@ func WrapUDPConn(admission admission.Admission, pc net.PacketConn) udp.Conn { } } +// RemoteAddr returns the remote address from the underlying connection +// if it implements the RemoteAddr interface. This is used for "connected" +// UDP sockets that have a fixed peer. func (c *udpConn) RemoteAddr() net.Addr { if nc, ok := c.PacketConn.(xnet.RemoteAddr); ok { return nc.RemoteAddr() @@ -129,6 +174,7 @@ func (c *udpConn) RemoteAddr() net.Addr { return nil } +// SetReadBuffer sets the socket receive buffer size. func (c *udpConn) SetReadBuffer(n int) error { if nc, ok := c.PacketConn.(xnet.SetBuffer); ok { return nc.SetReadBuffer(n) @@ -136,6 +182,7 @@ func (c *udpConn) SetReadBuffer(n int) error { return errUnsupport } +// SetWriteBuffer sets the socket send buffer size. func (c *udpConn) SetWriteBuffer(n int) error { if nc, ok := c.PacketConn.(xnet.SetBuffer); ok { return nc.SetWriteBuffer(n) @@ -143,6 +190,8 @@ func (c *udpConn) SetWriteBuffer(n int) error { return errUnsupport } +// Read delegates to the underlying connection's Read method if available +// (for connected UDP sockets that support stream-like reads). func (c *udpConn) Read(b []byte) (n int, err error) { if nc, ok := c.PacketConn.(io.Reader); ok { n, err = nc.Read(b) @@ -152,6 +201,8 @@ func (c *udpConn) Read(b []byte) (n int, err error) { return } +// ReadFrom reads the next packet from an admitted address, discarding +// packets from denied addresses. func (c *udpConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { for { n, addr, err = c.PacketConn.ReadFrom(p) @@ -166,6 +217,8 @@ func (c *udpConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { } } +// ReadFromUDP reads the next UDP packet from an admitted address. +// Packets from denied addresses are discarded transparently. func (c *udpConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { if nc, ok := c.PacketConn.(udp.ReadUDP); ok { for { @@ -184,6 +237,8 @@ func (c *udpConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { return } +// ReadMsgUDP reads a UDP packet with out-of-band data from an admitted +// address. Packets from denied addresses are silently skipped. func (c *udpConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error) { if nc, ok := c.PacketConn.(udp.ReadUDP); ok { for { @@ -202,6 +257,8 @@ func (c *udpConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAd return } +// Write delegates to the underlying connection's Write method if available +// (for connected UDP sockets). func (c *udpConn) Write(b []byte) (n int, err error) { if nc, ok := c.PacketConn.(io.Writer); ok { n, err = nc.Write(b) @@ -211,11 +268,15 @@ func (c *udpConn) Write(b []byte) (n int, err error) { return } +// WriteTo sends a packet to the specified address via the underlying +// packet connection. No admission check is performed on writes. func (c *udpConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { n, err = c.PacketConn.WriteTo(p, addr) return } +// WriteToUDP sends a UDP packet to the specified address if the +// underlying connection supports UDP-specific writes. func (c *udpConn) WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) { if nc, ok := c.PacketConn.(udp.WriteUDP); ok { n, err = nc.WriteToUDP(b, addr) @@ -225,6 +286,7 @@ func (c *udpConn) WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) { return } +// WriteMsgUDP sends a UDP packet with out-of-band data if supported. func (c *udpConn) WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error) { if nc, ok := c.PacketConn.(udp.WriteUDP); ok { n, oobn, err = nc.WriteMsgUDP(b, oob, addr) @@ -234,6 +296,8 @@ func (c *udpConn) WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, er return } +// SyscallConn exposes the underlying raw connection for socket-level +// operations if supported. func (c *udpConn) SyscallConn() (rc syscall.RawConn, err error) { if nc, ok := c.PacketConn.(xnet.SyscallConn); ok { return nc.SyscallConn() @@ -242,6 +306,9 @@ func (c *udpConn) SyscallConn() (rc syscall.RawConn, err error) { return } +// SetDSCP sets the Differentiated Services Code Point on the socket +// for traffic classification/QoS. Silently succeeds if not supported +// (best-effort). func (c *udpConn) SetDSCP(n int) error { if nc, ok := c.PacketConn.(xnet.SetDSCP); ok { return nc.SetDSCP(n) @@ -249,6 +316,7 @@ func (c *udpConn) SetDSCP(n int) error { return nil } +// Context returns the context carried by the underlying packet connection. func (c *udpConn) Context() context.Context { if innerCtx, ok := c.PacketConn.(ctx.Context); ok { return innerCtx.Context() diff --git a/admission/wrapper/listener.go b/admission/wrapper/listener.go index d47610ca..1b372840 100644 --- a/admission/wrapper/listener.go +++ b/admission/wrapper/listener.go @@ -1,3 +1,14 @@ +// Package wrapper provides net.Listener and net.Conn wrappers that +// enforce admission control at the network level. +// +// The listener wrapper checks each accepted connection against the +// admission controller before returning it to the caller. Denied +// connections are closed immediately and the listener continues +// accepting (transparent rejection). +// +// The connection wrappers (TCP, UDP, generic packet) check admission +// on each read operation, effectively dropping traffic from denied +// addresses without closing the underlying transport. package wrapper import ( @@ -9,13 +20,22 @@ import ( xctx "github.com/go-gost/x/ctx" ) +// listener wraps a net.Listener and performs admission checks on each +// accepted connection. Connections from denied addresses are silently +// closed and the accept loop continues. type listener struct { - service string + service string net.Listener admission admission.Admission log logger.Logger } +// WrapListener wraps a net.Listener with admission control. If admission +// is nil, the original listener is returned unchanged (no-op). +// +// The service name is passed to the admission controller via +// admission.WithService so that the controller can distinguish +// between different services sharing the same admission rules. func WrapListener(service string, admission admission.Admission, ln net.Listener) net.Listener { if admission == nil { return ln @@ -27,6 +47,16 @@ func WrapListener(service string, admission admission.Admission, ln net.Listener } } +// Accept blocks until a connection is accepted from the underlying +// listener, then checks it against the admission controller. Denied +// connections are closed and the loop retries. The caller never sees +// a rejected connection. +// +// The client address used for the admission check is determined by: +// 1. The srcAddr value from the connection's context (if available), +// which is the original client address before any proxy protocol +// or NAT rewriting. +// 2. Falling back to the raw RemoteAddr of the accepted connection. func (ln *listener) Accept() (net.Conn, error) { for { c, err := ln.Listener.Accept() @@ -34,6 +64,7 @@ func (ln *listener) Accept() (net.Conn, error) { return nil, err } + // Extract the context from the connection if it carries one. ctx := context.Background() if cc, ok := c.(xctx.Context); ok { if cv := cc.Context(); cv != nil { @@ -41,6 +72,8 @@ func (ln *listener) Accept() (net.Conn, error) { } } + // Prefer the original source address from context (e.g. set by + // proxy protocol handling), falling back to the raw remote address. clientAddr := c.RemoteAddr() if addr := xctx.SrcAddrFromContext(ctx); addr != nil { clientAddr = addr