sing-box/common/sniff/sniff.go

63 lines
1.5 KiB
Go
Raw Permalink Normal View History

2022-07-06 04:39:44 +00:00
package sniff
import (
2022-07-11 12:37:57 +00:00
"bytes"
2022-07-06 04:39:44 +00:00
"context"
"io"
2022-07-11 12:37:57 +00:00
"net"
"time"
2022-07-06 04:39:44 +00:00
"github.com/sagernet/sing-box/adapter"
2022-07-18 12:40:14 +00:00
C "github.com/sagernet/sing-box/constant"
2022-07-11 12:37:57 +00:00
"github.com/sagernet/sing/common/buf"
E "github.com/sagernet/sing/common/exceptions"
2022-07-06 04:39:44 +00:00
)
type (
2024-07-07 07:45:50 +00:00
StreamSniffer = func(ctx context.Context, metadata *adapter.InboundContext, reader io.Reader) error
PacketSniffer = func(ctx context.Context, metadata *adapter.InboundContext, packet []byte) error
2022-07-06 04:39:44 +00:00
)
2024-07-07 07:45:50 +00:00
func PeekStream(ctx context.Context, metadata *adapter.InboundContext, conn net.Conn, buffer *buf.Buffer, timeout time.Duration, sniffers ...StreamSniffer) error {
2022-10-07 12:30:27 +00:00
if timeout == 0 {
timeout = C.ReadPayloadTimeout
}
2023-08-24 03:07:22 +00:00
deadline := time.Now().Add(timeout)
2022-10-12 05:37:06 +00:00
var errors []error
2023-08-24 03:07:22 +00:00
for i := 0; i < 3; i++ {
err := conn.SetReadDeadline(deadline)
if err != nil {
2024-07-07 07:45:50 +00:00
return E.Cause(err, "set read deadline")
2023-08-24 03:07:22 +00:00
}
_, err = buffer.ReadOnceFrom(conn)
err = E.Errors(err, conn.SetReadDeadline(time.Time{}))
if err != nil {
if i > 0 {
break
}
2024-07-07 07:45:50 +00:00
return E.Cause(err, "read payload")
2023-08-24 03:07:22 +00:00
}
for _, sniffer := range sniffers {
2024-07-07 07:45:50 +00:00
err = sniffer(ctx, metadata, bytes.NewReader(buffer.Bytes()))
if err == nil {
return nil
2023-08-24 03:07:22 +00:00
}
errors = append(errors, err)
2022-07-06 04:39:44 +00:00
}
}
2024-07-07 07:45:50 +00:00
return E.Errors(errors...)
2022-07-06 04:39:44 +00:00
}
2024-07-07 07:45:50 +00:00
func PeekPacket(ctx context.Context, metadata *adapter.InboundContext, packet []byte, sniffers ...PacketSniffer) error {
2022-10-12 05:37:06 +00:00
var errors []error
2022-07-06 04:39:44 +00:00
for _, sniffer := range sniffers {
2024-07-07 07:45:50 +00:00
err := sniffer(ctx, metadata, packet)
if err == nil {
return nil
2022-07-06 04:39:44 +00:00
}
2022-10-12 05:37:06 +00:00
errors = append(errors, err)
2022-07-06 04:39:44 +00:00
}
2024-07-07 07:45:50 +00:00
return E.Errors(errors...)
2022-07-06 04:39:44 +00:00
}