Files
x/handler/http/udp.go
T
ginuerzh 23b58ddd23 refactor(handler/http): extract Authenticator, SnifferBuilder, and normalizeRequest as testable units
Extract three pure-logic components from httpHandler to eliminate I/O
coupling from auth and sniffing construction, enabling synchronous unit
tests and reducing per-request allocation in sniffAndHandle:

- Authenticator struct with AuthResult return type — auth decisions no
  longer write to the connection; callers handle response I/O. Auth
  tests drop net.Pipe/goroutines for direct return-value assertions.
- SnifferBuilder pre-built in Init and reused per-connection via Build(),
  replacing inline sniffing.Sniffer{} construction in sniffAndHandle.
- normalizeRequest extracted to util.go with NormalizedRequest type,
  collapsing 20 lines of inline URL/normalisation into a single call.
- knockMatch extracted as standalone pure function.
- clampBodySize exported as ClampBodySize for cross-package use.
- util_test.go with 22 tests covering utility functions.
- helpers_test.go consolidates shared test fakes (logger, observer, conn).
2026-05-29 00:14:44 +08:00

113 lines
2.9 KiB
Go

package http
import (
"bytes"
"context"
"errors"
"net"
"net/http"
"net/http/httputil"
"time"
"github.com/go-gost/core/logger"
stats "github.com/go-gost/core/observer/stats"
ictx "github.com/go-gost/x/internal/ctx"
"github.com/go-gost/x/internal/net/udp"
"github.com/go-gost/x/internal/util/socks"
xrecorder "github.com/go-gost/x/recorder"
)
// handleUDP implements UDP over HTTP (UDP relay). When the client sets the
// X-Gost-Protocol header to "udp", the handler responds with 200 OK and
// establishes a UDP association through the proxy chain. Client data sent
// over the HTTP connection is wrapped as SOCKS5 UDP packets and relayed
// through the UDP tunnel.
//
// If UDP relay is disabled (enableUDP=false), a 403 Forbidden is returned.
func (h *httpHandler) handleUDP(ctx context.Context, conn net.Conn, clientID string, ro *xrecorder.HandlerRecorderObject, log logger.Logger) error {
log = log.WithFields(map[string]any{
"cmd": "udp",
})
resp := &http.Response{
ProtoMajor: 1,
ProtoMinor: 1,
Header: h.md.header,
}
if resp.Header == nil {
resp.Header = http.Header{}
}
if !h.md.enableUDP {
resp.StatusCode = http.StatusForbidden
if log.IsLevelEnabled(logger.TraceLevel) {
dump, _ := httputil.DumpResponse(resp, false)
log.Trace(string(dump))
}
log.Error("http: UDP relay is disabled")
return resp.Write(conn)
}
resp.StatusCode = http.StatusOK
if log.IsLevelEnabled(logger.TraceLevel) {
dump, _ := httputil.DumpResponse(resp, false)
log.Trace(string(dump))
}
if err := resp.Write(conn); err != nil {
log.Error(err)
return err
}
if h.options.Observer != nil {
pstats := h.stats.Stats(clientID)
pstats.Add(stats.KindTotalConns, 1)
pstats.Add(stats.KindCurrentConns, 1)
defer pstats.Add(stats.KindCurrentConns, -1)
}
// Dial a UDP association through the proxy chain router. The empty
// address signals that the router should create a UDP socket rather
// than connect to a specific target.
if h.options.Router == nil {
return errors.New("nil router")
}
var buf bytes.Buffer
c, err := h.options.Router.Dial(ictx.ContextWithBuffer(ctx, &buf), "udp", "")
ro.Route = buf.String()
if err != nil {
log.Error(err)
return err
}
defer c.Close()
log.WithFields(map[string]any{"src": c.LocalAddr().String()})
ro.SrcAddr = c.LocalAddr().String()
pc, ok := c.(net.PacketConn)
if !ok {
err = errors.New("wrong connection type")
log.Error(err)
return err
}
// Wrap the HTTP connection as a SOCKS5 UDP tunnel server conn so
// that the relay can read/write SOCKS5-encapsulated UDP datagrams.
relay := udp.NewRelay(socks.UDPTunServerConn(conn), pc).
WithService(h.options.Service).
WithBypass(h.options.Bypass).
WithBufferSize(h.md.udpBufferSize).
WithLogger(log)
t := time.Now()
log.Infof("%s <-> %s", conn.RemoteAddr(), pc.LocalAddr())
relay.Run(ctx)
log.WithFields(map[string]any{
"duration": time.Since(t),
}).Infof("%s >-< %s", conn.RemoteAddr(), pc.LocalAddr())
return nil
}