sing-box/common/sniff/dns.go

58 lines
1.4 KiB
Go
Raw Normal View History

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