sing-box/common/sniff/sniff.go

79 lines
1.8 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"
"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 (
2024-07-07 15:45:50 +08: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 12:39:44 +08:00
)
2024-10-21 23:38:34 +08:00
func Skip(metadata *adapter.InboundContext) bool {
2024-08-28 11:40:43 +08:00
// skip server first protocols
switch metadata.Destination.Port {
case 25, 465, 587:
// SMTP
return true
case 143, 993:
// IMAP
return true
case 110, 995:
// POP3
return true
}
return false
}
2024-07-07 15:45:50 +08:00
func PeekStream(ctx context.Context, metadata *adapter.InboundContext, conn net.Conn, buffer *buf.Buffer, timeout time.Duration, sniffers ...StreamSniffer) error {
2022-10-07 20:30:27 +08:00
if timeout == 0 {
timeout = C.ReadPayloadTimeout
}
2023-08-24 11:07:22 +08:00
deadline := time.Now().Add(timeout)
2022-10-12 13:37:06 +08:00
var errors []error
2024-09-20 20:40:02 +08:00
for i := 0; ; i++ {
err := conn.SetReadDeadline(deadline)
if err != nil {
2024-07-07 15:45:50 +08:00
return E.Cause(err, "set read deadline")
2023-08-24 11:07:22 +08:00
}
2024-09-20 20:40:02 +08:00
_, err = buffer.ReadOnceFrom(conn)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
if i > 0 {
break
}
2024-07-07 15:45:50 +08:00
return E.Cause(err, "read payload")
2024-09-20 20:40:02 +08:00
}
errors = nil
for _, sniffer := range sniffers {
2024-07-07 15:45:50 +08:00
err = sniffer(ctx, metadata, bytes.NewReader(buffer.Bytes()))
if err == nil {
return nil
2024-09-20 20:40:02 +08:00
}
errors = append(errors, err)
2022-07-06 12:39:44 +08:00
}
}
2024-07-07 15:45:50 +08:00
return E.Errors(errors...)
2022-07-06 12:39:44 +08:00
}
2024-07-07 15:45:50 +08:00
func PeekPacket(ctx context.Context, metadata *adapter.InboundContext, packet []byte, sniffers ...PacketSniffer) error {
2022-10-12 13:37:06 +08:00
var errors []error
2022-07-06 12:39:44 +08:00
for _, sniffer := range sniffers {
2024-07-07 15:45:50 +08:00
err := sniffer(ctx, metadata, packet)
if err == nil {
return nil
2022-07-06 12:39:44 +08:00
}
2022-10-12 13:37:06 +08:00
errors = append(errors, err)
2022-07-06 12:39:44 +08:00
}
2024-07-07 15:45:50 +08:00
return E.Errors(errors...)
2022-07-06 12:39:44 +08:00
}