From f7f97ef625a3e504e4550f9399ddff7f4429798d Mon Sep 17 00:00:00 2001 From: Dreamacro <8615343+Dreamacro@users.noreply.github.com> Date: Wed, 10 Mar 2021 16:23:19 +0800 Subject: [PATCH] Fix: some HTTP proxy request broken --- adapters/inbound/http.go | 16 ++++++++++++++++ tunnel/connection.go | 4 +++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/adapters/inbound/http.go b/adapters/inbound/http.go index ee26ac7..72e8bb3 100644 --- a/adapters/inbound/http.go +++ b/adapters/inbound/http.go @@ -43,3 +43,19 @@ func RemoveHopByHopHeaders(header http.Header) { header.Del(strings.TrimSpace(h)) } } + +// RemoveExtraHTTPHostPort remove extra host port (example.com:80 --> example.com) +// It resolves the behavior of some HTTP servers that do not handle host:80 (e.g. baidu.com) +func RemoveExtraHTTPHostPort(req *http.Request) { + host := req.Host + if host == "" { + host = req.URL.Host + } + + if pHost, port, err := net.SplitHostPort(host); err == nil && port == "80" { + host = pHost + } + + req.Host = host + req.URL.Host = host +} diff --git a/tunnel/connection.go b/tunnel/connection.go index 5d46eb5..88d7c3b 100644 --- a/tunnel/connection.go +++ b/tunnel/connection.go @@ -20,11 +20,12 @@ import ( func handleHTTP(ctx *context.HTTPContext, outbound net.Conn) { req := ctx.Request() conn := ctx.Conn() - host := req.Host inboundReader := bufio.NewReader(conn) outboundReader := bufio.NewReader(outbound) + inbound.RemoveExtraHTTPHostPort(req) + host := req.Host for { keepAlive := strings.TrimSpace(strings.ToLower(req.Header.Get("Proxy-Connection"))) == "keep-alive" @@ -79,6 +80,7 @@ func handleHTTP(ctx *context.HTTPContext, outbound net.Conn) { break } + inbound.RemoveExtraHTTPHostPort(req) // Sometimes firefox just open a socket to process multiple domains in HTTP // The temporary solution is close connection when encountering different HOST if req.Host != host {