Only retry TCP sniffing for possible TLS Client Hello

This commit is contained in:
dyhkwong 2025-03-18 14:28:16 +08:00
parent 95e397f898
commit 085c6d0869
2 changed files with 15 additions and 5 deletions

View file

@ -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...)
}

View file

@ -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
}