Feature: Tunnel the device protocol through a reverse proxy over WebSocket

This commit is contained in:
yuanyuanxiang committed 2026-10-30 17:21:42 +01:00
1 parent de621aa555
commit d4f312c9d8
20 files changed
+1994 -63

No files matched your search

+76 -13
View File
@@ -42,6 +42,17 @@ type Config struct {
PerIPConnRateLimit int // max new connections per PerIPConnRateWindow per IP (0 = unlimited)
PerIPConnRateWindow time.Duration // window for PerIPConnRateLimit
// WebSocket transport. Devices that can only reach the server through a
// reverse proxy on a shared port (e.g. nginx on 443) upgrade to WebSocket;
// the device port then carries the unchanged app protocol inside binary
// frames. WSPath restricts the upgrade to one request path ("" = any).
WSPath string
// TrustedProxies lists the IPs/CIDRs whose X-Forwarded-For / X-Real-IP
// headers are believed. Only connections from these peers are allowed to
// report a different device address; empty defaults to loopback.
TrustedProxies []string
// TLSCertFile / TLSKeyFile enable optional one-way TLS on the device port.
// When both are set the server loads the cert and auto-detects TLS clients
// by their ClientHello; plaintext clients keep working unchanged. Both empty
@@ -87,6 +98,10 @@ type Server struct {
// wrapTLS consults it to sniff and wrap incoming connections.
tlsCfg *tls.Config
// trustedProxies are the peers allowed to report a device's real address
// via X-Forwarded-For / X-Real-IP (the reverse proxy in front of us).
trustedProxies []*net.IPNet
running atomic.Bool
wg sync.WaitGroup
ctx context.Context
@@ -109,6 +124,7 @@ func New(config Config) *Server {
cancel: cancel,
logger: logger.New(logger.DefaultConfig()).WithPrefix("Server"),
}
s.trustedProxies = parseTrustedProxies(config.TrustedProxies)
return s
}
@@ -356,38 +372,85 @@ func (s *Server) acceptLoop() {
continue
}
// Check connection limit before spawning goroutine
// Check connection limit before spawning goroutine.
if s.manager.Count() >= s.config.MaxConnections {
s.logger.Warn("Max connections reached, rejecting new connection from %s", conn.RemoteAddr())
_ = conn.Close()
continue
}
// Per-IP connection cap + accept rate. Rejecting here (before any
// buffer allocation or goroutine) is cheap, and a rejected device
// simply retries on its reconnect loop.
if !s.ipLimit.allow(peerIP(conn.RemoteAddr())) {
s.logger.Warn("Per-IP connection limit reached, rejecting %s", conn.RemoteAddr())
peer := peerIP(conn.RemoteAddr())
counted, allowed := s.limitDirectPeer(peer)
if !allowed {
s.logger.Warn("Per-IP connection limit reached, rejecting %s", peer)
_ = conn.Close()
continue
}
// Handle each connection in its own goroutine
go s.handleConnection(conn)
go s.handleConnection(conn, counted)
}
}
// handleConnection handles a single connection
func (s *Server) handleConnection(rawConn net.Conn) {
// limitDirectPeer applies the per-IP cap and accept rate to a freshly accepted
// peer, before the goroutine is spawned and before any sniffing read: a peer
// that opens sockets and never sends a full ClientHello / upgrade would
// otherwise hold a goroutine and a reader for up to ReadTimeout each, with no
// limit at all. Peers that are trusted proxies are exempt and report
// counted=false — every device behind a proxy arrives from the proxy's
// address, so they are limited later by the address their proxy reports.
func (s *Server) limitDirectPeer(peer string) (counted, allowed bool) {
if s.trustedProxy(peer) {
return false, true
}
if !s.ipLimit.allow(peer) {
return false, false
}
return true, true
}
// handleConnection handles a single connection. peerCapped reports whether
// acceptLoop already counted this peer against the per-IP limiter (direct
// peers only), in which case the count is released here when the connection
// ends.
func (s *Server) handleConnection(rawConn net.Conn, peerCapped bool) {
peer := peerIP(rawConn.RemoteAddr())
if peerCapped {
defer s.ipLimit.release(peer)
}
// Sniff and (when TLS is enabled) wrap TLS peers; plaintext passes through.
conn := s.wrapTLS(rawConn)
// Sniff for a WebSocket upgrade. Proxied devices (nginx on a shared port)
// arrive as a plaintext HTTP upgrade after the proxy terminated TLS.
conn, realIP := s.wrapWebSocket(conn, peer)
if conn == nil {
return
}
if !peerCapped {
// Proxied device: limit by the forwarded address so one device behind
// the proxy cannot consume the whole budget for everyone else.
limitIP := peer
if realIP != "" {
limitIP = realIP
}
if !s.ipLimit.allow(limitIP) {
s.logger.Warn("Per-IP connection limit reached, rejecting %s (peer %s)", limitIP, peer)
_ = conn.Close()
return
}
defer s.ipLimit.release(limitIP)
}
// Create context
ctx := connection.NewContext(conn, nil)
// Always release the per-IP slot on every exit path, including the
// manager.Add failure below (a rare accept/add race).
defer s.ipLimit.release(ctx.GetPeerIP())
if realIP != "" {
// Report the device's real address everywhere GetPeerIP is consulted
// (per-IP accounting, logging, ConnAuth sub-connection binding).
ctx.SetPeerIP(realIP)
}
// Add to manager
if err := s.manager.Add(ctx); err != nil {