diff --git a/common/sniff/sniff.go b/common/sniff/sniff.go index ecb0488b..0728b76e 100644 --- a/common/sniff/sniff.go +++ b/common/sniff/sniff.go @@ -3,6 +3,7 @@ package sniff import ( "bytes" "context" + goerrors "errors" "io" "net" "time" @@ -41,7 +42,7 @@ func PeekStream(ctx context.Context, metadata *adapter.InboundContext, conn net. } deadline := time.Now().Add(timeout) var errors []error - for i := 0; ; i++ { + for { err := conn.SetReadDeadline(deadline) if err != nil { return E.Cause(err, "set read deadline") @@ -49,9 +50,6 @@ func PeekStream(ctx context.Context, metadata *adapter.InboundContext, conn net. _, err = buffer.ReadOnceFrom(conn) _ = conn.SetReadDeadline(time.Time{}) if err != nil { - if i > 0 { - break - } return E.Cause(err, "read payload") } errors = nil @@ -65,6 +63,9 @@ func PeekStream(ctx context.Context, metadata *adapter.InboundContext, conn net. } errors = append(errors, err) } + if !goerrors.Is(E.Errors(errors...), errPossibleClientHello) { + break + } } return E.Errors(errors...) } diff --git a/common/sniff/tls.go b/common/sniff/tls.go index 6fe430e2..f81a0ee5 100644 --- a/common/sniff/tls.go +++ b/common/sniff/tls.go @@ -8,6 +8,12 @@ import ( "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing/common/bufio" + E "github.com/sagernet/sing/common/exceptions" +) + +var ( + errNotClientHello = E.New("not Client Hello") + errPossibleClientHello = E.New("may be Client Hello") ) func TLSClientHello(ctx context.Context, metadata *adapter.InboundContext, reader io.Reader) error { @@ -23,5 +29,8 @@ func TLSClientHello(ctx context.Context, metadata *adapter.InboundContext, reade metadata.Domain = clientHello.ServerName return nil } - return err + if _, ok := err.(tls.RecordHeaderError); ok { + return errNotClientHello + } + return errPossibleClientHello }