outbound.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package dns
  2. import (
  3. "context"
  4. "net"
  5. "os"
  6. "time"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/adapter/outbound"
  9. C "github.com/sagernet/sing-box/constant"
  10. "github.com/sagernet/sing-box/log"
  11. "github.com/sagernet/sing-box/option"
  12. "github.com/sagernet/sing/common/logger"
  13. M "github.com/sagernet/sing/common/metadata"
  14. N "github.com/sagernet/sing/common/network"
  15. "github.com/sagernet/sing/service"
  16. )
  17. func RegisterOutbound(registry *outbound.Registry) {
  18. outbound.Register[option.StubOptions](registry, C.TypeDNS, NewOutbound)
  19. }
  20. type Outbound struct {
  21. outbound.Adapter
  22. router adapter.DNSRouter
  23. logger logger.ContextLogger
  24. }
  25. func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.StubOptions) (adapter.Outbound, error) {
  26. return &Outbound{
  27. Adapter: outbound.NewAdapter(C.TypeDNS, tag, []string{N.NetworkTCP, N.NetworkUDP}, nil),
  28. router: service.FromContext[adapter.DNSRouter](ctx),
  29. logger: logger,
  30. }, nil
  31. }
  32. func (d *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  33. return nil, os.ErrInvalid
  34. }
  35. func (d *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  36. return nil, os.ErrInvalid
  37. }
  38. func (d *Outbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  39. metadata.Destination = M.Socksaddr{}
  40. for {
  41. conn.SetReadDeadline(time.Now().Add(C.DNSTimeout))
  42. err := HandleStreamDNSRequest(ctx, d.router, conn, metadata)
  43. if err != nil {
  44. conn.Close()
  45. if onClose != nil {
  46. onClose(err)
  47. }
  48. return
  49. }
  50. }
  51. }
  52. func (d *Outbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  53. NewDNSPacketConnection(ctx, d.router, conn, nil, metadata)
  54. }