From baf68026dcc126bccce4539d8d959603e265609c Mon Sep 17 00:00:00 2001 From: armv9 <48624112+arm64v8a@users.noreply.github.com> Date: Wed, 19 Apr 2023 03:14:04 +0000 Subject: [PATCH] sniff: fix http with port --- common/sniff/http.go | 8 +++++++- common/sniff/http_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 common/sniff/http_test.go diff --git a/common/sniff/http.go b/common/sniff/http.go index 9cd16624..ce47e6b5 100644 --- a/common/sniff/http.go +++ b/common/sniff/http.go @@ -4,6 +4,7 @@ import ( std_bufio "bufio" "context" "io" + "net" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" @@ -15,5 +16,10 @@ func HTTPHost(ctx context.Context, reader io.Reader) (*adapter.InboundContext, e if err != nil { return nil, err } - return &adapter.InboundContext{Protocol: C.ProtocolHTTP, Domain: request.Host}, nil + domain := request.Host + host, _, err := net.SplitHostPort(domain) + if err == nil { + domain = host + } + return &adapter.InboundContext{Protocol: C.ProtocolHTTP, Domain: domain}, nil } diff --git a/common/sniff/http_test.go b/common/sniff/http_test.go new file mode 100644 index 00000000..a0dcd304 --- /dev/null +++ b/common/sniff/http_test.go @@ -0,0 +1,27 @@ +package sniff_test + +import ( + "context" + "strings" + "testing" + + "github.com/sagernet/sing-box/common/sniff" + + "github.com/stretchr/testify/require" +) + +func TestHTTP1(t *testing.T) { + t.Parallel() + pkt := "GET / HTTP/1.1\r\nHost: www.google.com\r\nAccept: */*\r\n\r\n" + metadata, err := sniff.HTTPHost(context.Background(), strings.NewReader(pkt)) + require.NoError(t, err) + require.Equal(t, metadata.Domain, "www.google.com") +} + +func TestHTTP1WithPort(t *testing.T) { + t.Parallel() + pkt := "GET / HTTP/1.1\r\nHost: www.gov.cn:8080\r\nAccept: */*\r\n\r\n" + metadata, err := sniff.HTTPHost(context.Background(), strings.NewReader(pkt)) + require.NoError(t, err) + require.Equal(t, metadata.Domain, "www.gov.cn") +}