3246b39c93
Extract the 1024-line handler.go into concern-focused files:
util.go — 5 pure functions (decodeServerName, basicProxyAuth, upgradeType,
normalizeHostPort, buildConnectResponse) — 100% coverage
auth.go — authenticate (5 probe-resistance strategies + knock) + checkRateLimit
connect.go — handleConnect, sniffAndHandle, dial, setupTrafficLimiter
proxy.go — handleProxy keep-alive loop, proxyRoundTrip, handleUpgradeResponse
websocket.go — WebSocket frame sniffing/recording with rate-limited sampling
udp.go — UDP-over-HTTP relay with SOCKS5 tunnel
metadata.go — metadata struct, parseMetadata, probeResistance type
Key improvements:
- Transport injection (http.RoundTripper field) enables testing without real network
- Nil Router guards in dial, handleUDP, and nil Addr guard in checkRateLimit
- Pure functions converted from methods to package-level (no state dependency)
- setupTrafficLimiter returns cleanup closure to preserve defer lifetime
- handleConnect accepts caller's resp for correct recorder status capture
- Comprehensive package doc with full request-flow documentation
96 tests: 100% on pure functions, 86% on metadata parsing, 55% overall (integration
paths verified by e2e tests).
105 lines
2.7 KiB
Go
105 lines
2.7 KiB
Go
package http
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"time"
|
|
|
|
"github.com/go-gost/core/logger"
|
|
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, 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
|
|
}
|
|
|
|
// 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
|
|
}
|