sing-box/common/sniff/dns.go

56 lines
1.4 KiB
Go
Raw Normal View History

2022-07-06 12:39:44 +08:00
package sniff
import (
"context"
"encoding/binary"
"io"
"os"
"time"
2022-07-08 23:03:57 +08:00
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
2022-07-06 12:39:44 +08:00
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
2022-09-17 16:53:40 +08:00
M "github.com/sagernet/sing/common/metadata"
2022-07-06 12:39:44 +08:00
"github.com/sagernet/sing/common/task"
2022-07-06 15:01:09 +08:00
2022-09-13 16:18:39 +08:00
mDNS "github.com/miekg/dns"
2022-07-06 12:39:44 +08:00
)
2024-07-07 15:45:50 +08:00
func StreamDomainNameQuery(readCtx context.Context, metadata *adapter.InboundContext, reader io.Reader) error {
2022-07-06 12:39:44 +08:00
var length uint16
err := binary.Read(reader, binary.BigEndian, &length)
if err != nil {
2024-07-07 15:45:50 +08:00
return os.ErrInvalid
2022-07-06 12:39:44 +08:00
}
2022-08-26 13:13:44 +08:00
if length == 0 {
2024-07-07 15:45:50 +08:00
return os.ErrInvalid
2022-07-06 12:39:44 +08:00
}
2023-07-02 16:38:38 +08:00
buffer := buf.NewSize(int(length))
2022-07-06 12:39:44 +08:00
defer buffer.Release()
readCtx, cancel := context.WithTimeout(readCtx, time.Millisecond*100)
2022-08-03 17:11:53 +08:00
var readTask task.Group
readTask.Append0(func(ctx context.Context) error {
2022-07-06 12:39:44 +08:00
return common.Error(buffer.ReadFullFrom(reader, buffer.FreeLen()))
})
2022-08-03 17:11:53 +08:00
err = readTask.Run(readCtx)
2022-07-06 12:39:44 +08:00
cancel()
if err != nil {
2024-07-07 15:45:50 +08:00
return err
2022-07-06 12:39:44 +08:00
}
2024-07-07 15:45:50 +08:00
return DomainNameQuery(readCtx, metadata, buffer.Bytes())
2022-07-06 12:39:44 +08:00
}
2024-07-07 15:45:50 +08:00
func DomainNameQuery(ctx context.Context, metadata *adapter.InboundContext, packet []byte) error {
2022-09-13 16:18:39 +08:00
var msg mDNS.Msg
err := msg.Unpack(packet)
2022-07-06 12:39:44 +08:00
if err != nil {
2024-07-07 15:45:50 +08:00
return err
2022-07-06 12:39:44 +08:00
}
2022-09-17 16:53:40 +08:00
if len(msg.Question) == 0 || msg.Question[0].Qclass != mDNS.ClassINET || !M.IsDomainName(msg.Question[0].Name) {
2024-07-07 15:45:50 +08:00
return os.ErrInvalid
2022-09-17 16:53:40 +08:00
}
2024-07-07 15:45:50 +08:00
metadata.Protocol = C.ProtocolDNS
return nil
2022-07-06 12:39:44 +08:00
}