sing-box/common/sniff/sniff.go

53 lines
1.3 KiB
Go
Raw Normal View History

2022-07-06 12:39:44 +08:00
package sniff
import (
2022-07-11 20:37:57 +08:00
"bytes"
2022-07-06 12:39:44 +08:00
"context"
"io"
2022-07-11 20:37:57 +08:00
"net"
2022-07-06 12:39:44 +08:00
"os"
2022-07-11 20:37:57 +08:00
"time"
2022-07-06 12:39:44 +08:00
"github.com/sagernet/sing-box/adapter"
2022-07-18 20:40:14 +08:00
C "github.com/sagernet/sing-box/constant"
2022-07-11 20:37:57 +08:00
"github.com/sagernet/sing/common/buf"
E "github.com/sagernet/sing/common/exceptions"
2022-07-06 12:39:44 +08:00
)
type (
StreamSniffer = func(ctx context.Context, reader io.Reader) (*adapter.InboundContext, error)
PacketSniffer = func(ctx context.Context, packet []byte) (*adapter.InboundContext, error)
)
2022-07-11 20:37:57 +08:00
func PeekStream(ctx context.Context, conn net.Conn, buffer *buf.Buffer, sniffers ...StreamSniffer) (*adapter.InboundContext, error) {
2022-07-18 20:40:14 +08:00
err := conn.SetReadDeadline(time.Now().Add(C.ReadPayloadTimeout))
2022-07-11 20:37:57 +08:00
if err != nil {
return nil, err
}
_, err = buffer.ReadFrom(conn)
err = E.Errors(err, conn.SetReadDeadline(time.Time{}))
if err != nil {
return nil, err
}
var metadata *adapter.InboundContext
2022-07-06 12:39:44 +08:00
for _, sniffer := range sniffers {
2022-07-11 20:37:57 +08:00
metadata, err = sniffer(ctx, bytes.NewReader(buffer.Bytes()))
2022-07-06 12:39:44 +08:00
if err != nil {
continue
2022-07-06 12:39:44 +08:00
}
2022-07-11 20:37:57 +08:00
return metadata, nil
2022-07-06 12:39:44 +08:00
}
return nil, os.ErrInvalid
}
func PeekPacket(ctx context.Context, packet []byte, sniffers ...PacketSniffer) (*adapter.InboundContext, error) {
for _, sniffer := range sniffers {
sniffMetadata, err := sniffer(ctx, packet)
if err != nil {
continue
2022-07-06 12:39:44 +08:00
}
return sniffMetadata, nil
}
return nil, os.ErrInvalid
}