sing-box/common/sniff/sniff.go

79 lines
1.8 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-10-21 15:38:34 +00:00
func Skip(metadata *adapter.InboundContext) bool {
2024-08-28 03:40:43 +00: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 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
2024-09-20 12:40:02 +00:00
for i := 0; ; 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
}
2024-09-20 12:40:02 +00:00
_, err = buffer.ReadOnceFrom(conn)
_ = 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")
2024-09-20 12:40:02 +00:00
}
errors = nil
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
2024-09-20 12:40:02 +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
}