Files
x/internal/net/proxyproto/conn.go
T
ginuerzh 0e96f602fa fix(matcher,plugin): case-insensitive matching, port accumulation, nil guards, doc comments
matcher: fix IPv6 normalization via netip.ParseAddr, port-range overwrite
by switching to []*PortRange map, case-insensitive domain/host matching,
glob.MustCompile→Compile to avoid panic on invalid patterns.

plugin: guard nil *Options in NewGRPCConn and NewHTTPClient; add
HTTPClientTransport helper for idle-connection cleanup.

net/*: add doc comments for all exported symbols (no code changes).

Add 30 tests (matcher_test.go 22, plugin_test.go 8) covering all
matcher types, nil safety, case insensitivity, IPv6 normalization,
port ranges, and plugin option composition.
2026-05-24 18:18:42 +08:00

106 lines
2.0 KiB
Go

package proxyproto
import (
"context"
"net"
"strconv"
xio "github.com/go-gost/x/internal/io"
proxyproto "github.com/pires/go-proxyproto"
)
type serverConn struct {
net.Conn
ctx context.Context
}
func (c *serverConn) Context() context.Context {
return c.ctx
}
func (c *serverConn) RemoteAddr() net.Addr {
if conn, ok := c.Conn.(*proxyproto.Conn); ok {
return conn.Raw().RemoteAddr()
}
return c.Conn.RemoteAddr()
}
func (c *serverConn) LocalAddr() net.Addr {
if conn, ok := c.Conn.(*proxyproto.Conn); ok {
return conn.Raw().LocalAddr()
}
return c.Conn.LocalAddr()
}
func (c *serverConn) CloseRead() error {
if sc, ok := c.Conn.(xio.CloseRead); ok {
return sc.CloseRead()
}
if conn, ok := c.Conn.(*proxyproto.Conn); ok {
if tcpConn, ok := conn.TCPConn(); ok {
return tcpConn.CloseRead()
}
}
return xio.ErrUnsupported
}
func (c *serverConn) CloseWrite() error {
if sc, ok := c.Conn.(xio.CloseWrite); ok {
return sc.CloseWrite()
}
if conn, ok := c.Conn.(*proxyproto.Conn); ok {
if tcpConn, ok := conn.TCPConn(); ok {
return tcpConn.CloseWrite()
}
}
return xio.ErrUnsupported
}
// WrapClientConn writes a PROXY protocol header to c using src and dst
// addresses, then returns c for continued use. If ppv is <= 0 or either
// address is nil, the connection is returned unchanged.
func WrapClientConn(ppv int, src, dst net.Addr, c net.Conn) net.Conn {
if ppv <= 0 || c == nil {
return c
}
if src = convertAddr(src); src == nil {
return c
}
if dst = convertAddr(dst); dst == nil {
return c
}
header := proxyproto.HeaderProxyFromAddrs(byte(ppv), src, dst)
header.WriteTo(c)
return c
}
func convertAddr(addr net.Addr) net.Addr {
if addr == nil {
return nil
}
host, sp, _ := net.SplitHostPort(addr.String())
ip := net.ParseIP(host)
port, _ := strconv.Atoi(sp)
if ip == nil || ip.Equal(net.IPv6zero) {
ip = net.IPv4zero
}
switch addr.Network() {
case "tcp", "tcp4", "tcp6":
return &net.TCPAddr{
IP: ip,
Port: port,
}
default:
return &net.UDPAddr{
IP: ip,
Port: port,
}
}
}