outbound.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. )
  16. func RegisterOutbound(registry *outbound.Registry) {
  17. outbound.Register[option.StubOptions](registry, C.TypeDNS, NewOutbound)
  18. }
  19. type Outbound struct {
  20. outbound.Adapter
  21. router adapter.Router
  22. logger logger.ContextLogger
  23. }
  24. func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.StubOptions) (adapter.Outbound, error) {
  25. return &Outbound{
  26. Adapter: outbound.NewAdapter(C.TypeDNS, tag, []string{N.NetworkTCP, N.NetworkUDP}, nil),
  27. router: router,
  28. logger: logger,
  29. }, nil
  30. }
  31. func (d *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  32. return nil, os.ErrInvalid
  33. }
  34. func (d *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  35. return nil, os.ErrInvalid
  36. }
  37. func (d *Outbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  38. metadata.Destination = M.Socksaddr{}
  39. for {
  40. conn.SetReadDeadline(time.Now().Add(C.DNSTimeout))
  41. err := HandleStreamDNSRequest(ctx, d.router, conn, metadata)
  42. if err != nil {
  43. conn.Close()
  44. if onClose != nil {
  45. onClose(err)
  46. }
  47. return
  48. }
  49. }
  50. }
  51. func (d *Outbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  52. NewDNSPacketConnection(ctx, d.router, conn, nil, metadata)
  53. }