{"modulePath":"github.com/dolfly/x","version":"v0.28.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package http\n\nPackage 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.\n\nThe handler is registered under the name \"http\" and created via NewHandler in init().\n\n### Request processing flow {#hdr-Request_processing_flow}\n\nEach 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:\n\n\tHandle()\n\t  ├─ stats.WrapConn (per-connection I/O counters)\n\t  ├─ checkRateLimit (connection rate limiter, if configured)\n\t  ├─ http.ReadRequest\n\t  ├─ xhttp.GetClientIP (extract client IP from headers)\n\t  └─ handleRequest()\n\n### Request dispatch (handleRequest) {#hdr-Request_dispatch__handleRequest_}\n\nhandleRequest is the central dispatcher. It normalises the request and routes to one of three code paths:\n\n 1. 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\".\n\n 2. 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\".\n\n 3. TNET v2 compatibility — decodes Tnet-Target and X-Tnet-Target headers (base64+CRC32 encoding) to recover the actual target host from older TNET clients.\n\n 4. Host normalisation — appends \":80\" if no port is present.\n\n 5. Authentication — see \"Authentication and probe resistance\" below.\n\n 6. Bypass check — if a bypass matcher is configured and the target address matches, a 403 Forbidden is returned.\n\n 7. Routing: • X-Tnet-Protocol: udp → handleUDP • setupTrafficLimiter wraps the conn (per-client shaping + observer stats) • Method != CONNECT → handleProxy (forward proxy) • Method == CONNECT → handleConnect (tunnel)\n\n### Forward proxy path (handleProxy → proxyRoundTrip) {#hdr-Forward_proxy_path__handleProxy___proxyRoundTrip_}\n\nhandleProxy 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.\n\nproxyRoundTrip performs a single HTTP round-trip:\n\n  - Clones the recorder object for per-request isolation.\n  - Normalises the host (adds default port if missing).\n  - Handles HTTP/1.0 compatibility (Connection: keep-alive / close).\n  - Strips proxy-specific headers: Proxy-Authorization, Proxy-Connection, Tnet-Target, X-Tnet-Target.\n  - Checks bypass rules (403 Forbidden on match).\n  - Optionally intercepts the request body for recording (tee reader).\n  - Sends the request through the upstream http.Transport (which dials through the proxy chain router via h.dial).\n  - Optionally intercepts the response body for recording.\n  - Handles 101 Switching Protocols (see \"WebSocket upgrade\" below).\n  - Writes the response to the client.\n\n### CONNECT tunnel path (handleConnect → sniffAndHandle) {#hdr-CONNECT_tunnel_path__handleConnect___sniffAndHandle_}\n\nhandleConnect implements the HTTP CONNECT tunnel:\n\n 1. Dials the target address through the proxy chain router (h.dial).\n 2. On dial failure, writes a 503 Service Unavailable to the client.\n 3. Writes \"200 Connection established\" to the client.\n 4. If sniffing is enabled, calls sniffAndHandle to inspect the initial bytes from the client.\n 5. If sniffAndHandle does not claim the connection, falls back to raw bidirectional pipe forwarding (xnet.Pipe).\n\nsniffAndHandle peeks at the client's initial bytes:\n\n  - Sets a read deadline (sniffing.timeout) to bound the peek.\n  - Calls sniffing.Sniff to classify the protocol.\n  - For HTTP traffic: delegates to sniffer.HandleHTTP (HTTP request routing through the tunnel).\n  - For TLS traffic: delegates to sniffer.HandleTLS (MITM decryption if certificates are configured, or blind forwarding).\n  - For unrecognised protocols: returns (false, nil), and the caller falls back to raw pipe forwarding.\n  - 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.\n\n### WebSocket upgrade (handleUpgradeResponse) {#hdr-WebSocket_upgrade__handleUpgradeResponse_}\n\nWhen proxyRoundTrip receives a 101 Switching Protocols response:\n\n 1. Validates that the request and response upgrade types match.\n 2. Extracts the backend connection from the response body (the HTTP transport upgrades the connection on 101).\n 3. Writes the 101 response to the client.\n 4. If the upgrade is \"websocket\" and sniffing.websocket is enabled, starts frame-level recording via sniffingWebsocketFrame.\n 5. Otherwise, falls back to raw bidirectional pipe forwarding.\n\nsniffingWebsocketFrame 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.\n\n### Authentication and probe resistance (authenticate) {#hdr-Authentication_and_probe_resistance__authenticate_}\n\nauthenticate extracts credentials from the Proxy-Authorization header (HTTP Basic auth) and validates them against the configured Auther.\n\nWhen no Auther is configured, all requests are anonymous (id=\"\", ok=true).\n\nWhen 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:\n\n\tcode:  respond with a custom HTTP status code  (e.g. \"code:404\")\n\tweb:   fetch a URL and replay its response       (e.g. \"web:example.com\")\n\thost:  forward the raw request to a decoy host   (e.g. \"host:1.2.3.4:80\")\n\tfile:  serve a local file with Content-Type: text/html\n\nThe 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.\n\n### UDP relay (handleUDP) {#hdr-UDP_relay__handleUDP_}\n\nWhen X-Tnet-Protocol is \"udp\":\n\n  - If enableUDP is false, a 403 Forbidden is returned.\n  - 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.\n\n### Upstream dialing (dial) {#hdr-Upstream_dialing__dial_}\n\ndial 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.\n\n### Initialisation (Init) {#hdr-Initialisation__Init_}\n\nInit 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.\n\n### Observability {#hdr-Observability}\n\nPer-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.\n\n### Key configuration (metadata) {#hdr-Key_configuration__metadata_}\n\n\treadTimeout:      upstream response header timeout (default 15s, negative disables)\n\tidleTimeout:      pipe forwarding idle timeout (0 = disabled)\n\tkeepalive:        enable HTTP keep-alive on the upstream transport\n\tcompression:      enable HTTP compression on the upstream transport\n\tprobeResist:      decoy response on auth failure (format \"type:value\")\n\tknock:            secret hostname that bypasses probe resistance\n\tudp:              enable UDP relay\n\tsniffing:         enable protocol sniffing on CONNECT tunnels\n\tsniffing.timeout: read deadline for the initial sniff peek\n\tsniffing.websocket: enable WebSocket frame recording\n\tsniffing.websocket.sampleRate: max frames recorded per second\n\tmitm.certFile / mitm.keyFile: CA certificate pair for TLS decryption\n\tmitm.bypass:      named bypass matcher to skip MITM decryption\n\thash:             hop selection strategy (\"host\" for consistent hashing)\n\tobserverPeriod:   stats reporting interval (default 5s, min 1s)\n\tproxyAgent:       Proxy-Agent header value (default \"tnet/3.0\")\n\n## Functions\n\n```go\nfunc NewHandler(opts ...handler.Option) handler.Handler\n```\nNewHandler creates a new HTTP handler and applies the given options. It is called by the registry when a service references the \"http\" handler.\n\n## Types\n\n```go\ntype AuthResult struct {\n\tClientID string\n\tOK       bool\n\tResponse *http.Response // non-nil when !OK (407 or probe-resistance decoy)\n\tPipeTo   string         // non-empty when pr.Type==\"host\"; caller dials+pipes\n}\n```\nAuthResult 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.\n\n```go\ntype Authenticator struct {\n\tAuther    auth.Authenticator\n\tPR        *probeResistance\n\tRealm     string\n\tService   string                               // service name passed to auth.WithService\n\tWebClient func(string) (*http.Response, error) // injectable for tests; defaults to http.Get\n\tLog       logger.Logger\n}\n```\nAuthenticator 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.\n\n```go\nfunc (a *Authenticator) Authenticate(ctx context.Context, req *http.Request) *AuthResult\n```\nAuthenticate 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.\n\nThe \"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.\n\n```go\ntype NormalizedRequest struct {\n\tNetwork string // \"tcp\" or \"udp\"\n\tAddr    string // host:port (default port appended when absent)\n}\n```\nNormalizedRequest holds the parsed target address and network from an HTTP proxy request after URL inference, TNET v2 compatibility decoding, and host normalisation.\n\n```go\ntype SnifferBuilder struct {\n\tWebsocket           bool\n\tWebsocketSampleRate float64\n\tRecorder            recorder.Recorder\n\tSessionRecorder     *xrecorder.SessionRecorder\n\tRecorderOptions     *recorder.Options\n\tCertificate         *x509.Certificate\n\tPrivateKey          crypto.PrivateKey\n\tALPN                string\n\tCertPool            tls_util.CertPool\n\tMitmBypass          bypass.Bypass\n\t// ReadTimeout is the timeout for reading upstream HTTP response headers\n\t// and TLS ServerHello during sniffing. Passed through to sniffing.Sniffer.\n\t// See sniffing.Sniffer.ReadTimeout for details.\n\tReadTimeout time.Duration\n\t// Cache is the HTTP response cache (nil when caching is disabled).\n\tCache *httpcache.Cache\n}\n```\nSnifferBuilder holds all configuration needed to construct a sniffing.Sniffer. It is populated once during Init and reused for each sniffed connection.\n\n```go\nfunc (b *SnifferBuilder) Build() *sniffing.Sniffer\n```\nBuild creates a new sniffing.Sniffer from the builder's configuration.\n\n","path":"github.com/dolfly/x/handler/http","name":"http","synopsis":"Package http implements an HTTP/HTTPS proxy handler.","isRedistributable":true}
