Documentation
¶
Overview ¶
Package http implements an HTTP/HTTPS proxy handler. It supports both forward proxy (GET/POST/CONNECT) and tunnel modes with optional TLS sniffing, MITM decryption, WebSocket frame recording, probe resistance, and UDP relay.
The handler is registered under the name "http" and created via NewHandler in init().
Request processing flow ¶
Each inbound net.Conn is handled by Handle, which reads exactly one HTTP request and delegates to handleRequest for routing. The flow through the handler proceeds as follows:
Handle() ├─ stats.WrapConn (per-connection I/O counters) ├─ checkRateLimit (connection rate limiter, if configured) ├─ http.ReadRequest ├─ xhttp.GetClientIP (extract client IP from headers) └─ handleRequest()
Request dispatch (handleRequest) ¶
handleRequest is the central dispatcher. It normalises the request and routes to one of three code paths:
URL scheme inference — if the URL is not absolute (plain HTTP proxy request), the Host header is validated with govalidator. A valid DNS name or IP address implies the scheme is "http".
Network detection — reads the X-Tnet-Protocol header. If the value is "udp" the request is treated as a UDP relay; otherwise it defaults to "tcp".
TNET v2 compatibility — decodes Tnet-Target and X-Tnet-Target headers (base64+CRC32 encoding) to recover the actual target host from older TNET clients.
Host normalisation — appends ":80" if no port is present.
Authentication — see "Authentication and probe resistance" below.
Bypass check — if a bypass matcher is configured and the target address matches, a 403 Forbidden is returned.
Routing: • X-Tnet-Protocol: udp → handleUDP • setupTrafficLimiter wraps the conn (per-client shaping + observer stats) • Method != CONNECT → handleProxy (forward proxy) • Method == CONNECT → handleConnect (tunnel)
Forward proxy path (handleProxy → proxyRoundTrip) ¶
handleProxy wraps the connection with per-request stats, performs the first round-trip via proxyRoundTrip, then enters a keep-alive loop reading and proxying subsequent requests on the same connection until the client or upstream closes.
proxyRoundTrip performs a single HTTP round-trip:
- Clones the recorder object for per-request isolation.
- Normalises the host (adds default port if missing).
- Handles HTTP/1.0 compatibility (Connection: keep-alive / close).
- Strips proxy-specific headers: Proxy-Authorization, Proxy-Connection, Tnet-Target, X-Tnet-Target.
- Checks bypass rules (403 Forbidden on match).
- Optionally intercepts the request body for recording (tee reader).
- Sends the request through the upstream http.Transport (which dials through the proxy chain router via h.dial).
- Optionally intercepts the response body for recording.
- Handles 101 Switching Protocols (see "WebSocket upgrade" below).
- Writes the response to the client.
CONNECT tunnel path (handleConnect → sniffAndHandle) ¶
handleConnect implements the HTTP CONNECT tunnel:
- Dials the target address through the proxy chain router (h.dial).
- On dial failure, writes a 503 Service Unavailable to the client.
- Writes "200 Connection established" to the client.
- If sniffing is enabled, calls sniffAndHandle to inspect the initial bytes from the client.
- If sniffAndHandle does not claim the connection, falls back to raw bidirectional pipe forwarding (xnet.Pipe).
sniffAndHandle peeks at the client's initial bytes:
- Sets a read deadline (sniffing.timeout) to bound the peek.
- Calls sniffing.Sniff to classify the protocol.
- For HTTP traffic: delegates to sniffer.HandleHTTP (HTTP request routing through the tunnel).
- For TLS traffic: delegates to sniffer.HandleTLS (MITM decryption if certificates are configured, or blind forwarding).
- For unrecognised protocols: returns (false, nil), and the caller falls back to raw pipe forwarding.
- Both sniff handlers receive dial closures that return the already-established upstream connection, so the sniffer uses the same tunnel rather than opening a new one.
WebSocket upgrade (handleUpgradeResponse) ¶
When proxyRoundTrip receives a 101 Switching Protocols response:
- Validates that the request and response upgrade types match.
- Extracts the backend connection from the response body (the HTTP transport upgrades the connection on 101).
- Writes the 101 response to the client.
- If the upgrade is "websocket" and sniffing.websocket is enabled, starts frame-level recording via sniffingWebsocketFrame.
- Otherwise, falls back to raw bidirectional pipe forwarding.
sniffingWebsocketFrame runs two goroutines (one per direction) that read WebSocket frames, record metadata and optionally the payload (subject to a rate limiter with sniffing.websocket.sampleRate), and forward the frames to the peer. The first direction to encounter an error terminates the relay.
Authentication and probe resistance (authenticate) ¶
authenticate extracts credentials from the Proxy-Authorization header (HTTP Basic auth) and validates them against the configured Auther.
When no Auther is configured, all requests are anonymous (id="", ok=true).
When authentication fails and probeResistance is configured, the handler returns a decoy response instead of the normal 407 Proxy-Auth-Required, making the port appear to run a different service. Four strategies are supported:
code: respond with a custom HTTP status code (e.g. "code:404") web: fetch a URL and replay its response (e.g. "web:example.com") host: forward the raw request to a decoy host (e.g. "host:1.2.3.4:80") file: serve a local file with Content-Type: text/html
The knock feature (pr.Knock) restricts probe resistance to clients that don't know a secret hostname. When pr.Knock is set and the request hostname matches, probe resistance is bypassed and the normal 407 is returned — revealing the proxy only to clients that know the knock address.
UDP relay (handleUDP) ¶
When X-Tnet-Protocol is "udp":
- If enableUDP is false, a 403 Forbidden is returned.
- Otherwise a 200 OK is written, a UDP association is dialled through the proxy chain router, and the HTTP connection is wrapped as a SOCKS5 UDP tunnel. Client data is read as SOCKS5-encapsulated UDP datagrams and relayed through the chain.
Upstream dialing (dial) ¶
dial establishes upstream connections through the proxy chain router. It attaches the recorder object and logger from the context and, when h.md.hash is "host", sets the target address as the hash source for consistent hop selection. The route taken is written to the recorder object via the context buffer.
Initialisation (Init) ¶
Init parses metadata, creates a cached traffic limiter, starts the background stats observer goroutine, picks the first service-handler recorder, initialises the MITM certificate pool (if mitm.certFile and mitm.keyFile are both provided), and builds the upstream http.Transport. The transport dials through the proxy chain via h.dial.
Observability ¶
Per-connection stats are tracked via stats_wrapper.WrapConn in Handle. Per-client stats (KindTotalConns, KindCurrentConns) are tracked in setupTrafficLimiter and published to the configured Observer on a periodic ticker (observerPeriod, default 5s, min 1s). The observeStats goroutine retries previously failed events before sending new ones.
Key configuration (metadata) ¶
readTimeout: upstream response header timeout (default 15s, negative disables)
idleTimeout: pipe forwarding idle timeout (0 = disabled)
keepalive: enable HTTP keep-alive on the upstream transport
compression: enable HTTP compression on the upstream transport
probeResist: decoy response on auth failure (format "type:value")
knock: secret hostname that bypasses probe resistance
udp: enable UDP relay
sniffing: enable protocol sniffing on CONNECT tunnels
sniffing.timeout: read deadline for the initial sniff peek
sniffing.websocket: enable WebSocket frame recording
sniffing.websocket.sampleRate: max frames recorded per second
mitm.certFile / mitm.keyFile: CA certificate pair for TLS decryption
mitm.bypass: named bypass matcher to skip MITM decryption
hash: hop selection strategy ("host" for consistent hashing)
observerPeriod: stats reporting interval (default 5s, min 1s)
proxyAgent: Proxy-Agent header value (default "tnet/3.0")
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AuthResult ¶ added in v0.28.1
type AuthResult struct {
ClientID string
OK bool
Response *http.Response // non-nil when !OK (407 or probe-resistance decoy)
PipeTo string // non-empty when pr.Type=="host"; caller dials+pipes
}
AuthResult is returned by Authenticator.Authenticate. When OK is false, Response is the HTTP response to write to the client (407 or a probe- resistance decoy). When PipeTo is non-empty, the caller must dial the given address, pipe the raw request through it, and return immediately — the connection is consumed by host-mode probe resistance.
type Authenticator ¶ added in v0.28.1
type Authenticator struct {
Auther auth.Authenticator
PR *probeResistance
Realm string
Service string // service name passed to auth.WithService
WebClient func(string) (*http.Response, error) // injectable for tests; defaults to http.Get
Log logger.Logger
}
Authenticator validates Proxy-Authorization headers and generates probe- resistance decoy responses on failure. It does not perform I/O — the caller is responsible for writing the returned response or dialling the PipeTo target.
func (*Authenticator) Authenticate ¶ added in v0.28.1
func (a *Authenticator) Authenticate(ctx context.Context, req *http.Request) *AuthResult
Authenticate validates the client's credentials and returns an AuthResult. When no Auther is configured, all requests are anonymous (OK=true). On auth failure, if probe resistance is configured, a decoy response is built; otherwise a standard 407 Proxy-Auth-Required is returned.
The "host" probe resistance strategy is signalled via PipeTo rather than handled inline — the caller must dial the PipeTo address and pipe the raw request through it. All other strategies produce a Response.
type NormalizedRequest ¶ added in v0.28.1
type NormalizedRequest struct {
Network string // "tcp" or "udp"
Addr string // host:port (default port appended when absent)
}
NormalizedRequest holds the parsed target address and network from an HTTP proxy request after URL inference, TNET v2 compatibility decoding, and host normalisation.
type SnifferBuilder ¶ added in v0.28.1
type SnifferBuilder struct {
Websocket bool
WebsocketSampleRate float64
Recorder recorder.Recorder
SessionRecorder *xrecorder.SessionRecorder
RecorderOptions *recorder.Options
Certificate *x509.Certificate
PrivateKey crypto.PrivateKey
ALPN string
CertPool tls_util.CertPool
MitmBypass bypass.Bypass
// ReadTimeout is the timeout for reading upstream HTTP response headers
// and TLS ServerHello during sniffing. Passed through to sniffing.Sniffer.
// See sniffing.Sniffer.ReadTimeout for details.
ReadTimeout time.Duration
// Cache is the HTTP response cache (nil when caching is disabled).
Cache *httpcache.Cache
}
SnifferBuilder holds all configuration needed to construct a sniffing.Sniffer. It is populated once during Init and reused for each sniffed connection.
func (*SnifferBuilder) Build ¶ added in v0.28.1
func (b *SnifferBuilder) Build() *sniffing.Sniffer
Build creates a new sniffing.Sniffer from the builder's configuration.