inbound.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package direct
  2. import (
  3. "context"
  4. "net"
  5. "os"
  6. "time"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/adapter/inbound"
  9. "github.com/sagernet/sing-box/common/listener"
  10. C "github.com/sagernet/sing-box/constant"
  11. "github.com/sagernet/sing-box/log"
  12. "github.com/sagernet/sing-box/option"
  13. "github.com/sagernet/sing/common/buf"
  14. "github.com/sagernet/sing/common/bufio"
  15. M "github.com/sagernet/sing/common/metadata"
  16. N "github.com/sagernet/sing/common/network"
  17. "github.com/sagernet/sing/common/udpnat2"
  18. )
  19. func RegisterInbound(registry *inbound.Registry) {
  20. inbound.Register[option.DirectInboundOptions](registry, C.TypeDirect, NewInbound)
  21. }
  22. type Inbound struct {
  23. inbound.Adapter
  24. ctx context.Context
  25. router adapter.ConnectionRouterEx
  26. logger log.ContextLogger
  27. listener *listener.Listener
  28. udpNat *udpnat.Service
  29. overrideOption int
  30. overrideDestination M.Socksaddr
  31. }
  32. func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.DirectInboundOptions) (adapter.Inbound, error) {
  33. options.UDPFragmentDefault = true
  34. inbound := &Inbound{
  35. Adapter: inbound.NewAdapter(C.TypeDirect, tag),
  36. ctx: ctx,
  37. router: router,
  38. logger: logger,
  39. }
  40. if options.OverrideAddress != "" && options.OverridePort != 0 {
  41. inbound.overrideOption = 1
  42. inbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort)
  43. } else if options.OverrideAddress != "" {
  44. inbound.overrideOption = 2
  45. inbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort)
  46. } else if options.OverridePort != 0 {
  47. inbound.overrideOption = 3
  48. inbound.overrideDestination = M.Socksaddr{Port: options.OverridePort}
  49. }
  50. var udpTimeout time.Duration
  51. if options.UDPTimeout != 0 {
  52. udpTimeout = time.Duration(options.UDPTimeout)
  53. } else {
  54. udpTimeout = C.UDPTimeout
  55. }
  56. inbound.udpNat = udpnat.New(inbound, inbound.preparePacketConnection, udpTimeout, false)
  57. inbound.listener = listener.New(listener.Options{
  58. Context: ctx,
  59. Logger: logger,
  60. Network: options.Network.Build(),
  61. Listen: options.ListenOptions,
  62. ConnectionHandler: inbound,
  63. PacketHandler: inbound,
  64. })
  65. return inbound, nil
  66. }
  67. func (i *Inbound) Start(stage adapter.StartStage) error {
  68. if stage != adapter.StartStateStart {
  69. return nil
  70. }
  71. return i.listener.Start()
  72. }
  73. func (i *Inbound) Close() error {
  74. return i.listener.Close()
  75. }
  76. func (i *Inbound) NewPacket(buffer *buf.Buffer, source M.Socksaddr) {
  77. i.udpNat.NewPacket([][]byte{buffer.Bytes()}, source, i.listener.UDPAddr(), nil)
  78. }
  79. func (i *Inbound) NewPacketBatch(buffers []*buf.Buffer, sources []M.Socksaddr) {
  80. i.udpNat.NewPacketBatch(buffers, sources, i.listener.UDPAddr(), nil)
  81. }
  82. func (i *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  83. metadata.Inbound = i.Tag()
  84. metadata.InboundType = i.Type()
  85. destination := metadata.OriginDestination
  86. switch i.overrideOption {
  87. case 1:
  88. destination = i.overrideDestination
  89. case 2:
  90. destination.Addr = i.overrideDestination.Addr
  91. case 3:
  92. destination.Port = i.overrideDestination.Port
  93. }
  94. metadata.Destination = destination
  95. if i.overrideOption != 0 {
  96. i.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  97. }
  98. i.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  99. }
  100. func (i *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  101. i.logger.InfoContext(ctx, "inbound packet connection from ", source)
  102. var metadata adapter.InboundContext
  103. metadata.Inbound = i.Tag()
  104. metadata.InboundType = i.Type()
  105. //nolint:staticcheck
  106. metadata.InboundDetour = i.listener.ListenOptions().Detour
  107. //nolint:staticcheck
  108. metadata.Source = source
  109. destination = i.listener.UDPAddr()
  110. switch i.overrideOption {
  111. case 1:
  112. destination = i.overrideDestination
  113. case 2:
  114. destination.Addr = i.overrideDestination.Addr
  115. case 3:
  116. destination.Port = i.overrideDestination.Port
  117. default:
  118. }
  119. i.logger.InfoContext(ctx, "inbound packet connection to ", destination)
  120. metadata.Destination = destination
  121. if i.overrideOption != 0 {
  122. conn = bufio.NewDestinationNATPacketConn(bufio.NewNetPacketConn(conn), i.listener.UDPAddr(), destination)
  123. }
  124. i.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  125. }
  126. func (i *Inbound) preparePacketConnection(source M.Socksaddr, destination M.Socksaddr, userData any) (bool, context.Context, N.PacketWriter, N.CloseHandlerFunc) {
  127. return true, log.ContextWithNewID(i.ctx), &directPacketWriter{i.listener.PacketWriter(), source}, nil
  128. }
  129. type directPacketWriter struct {
  130. writer N.PacketWriter
  131. source M.Socksaddr
  132. }
  133. func (w *directPacketWriter) WritePacket(buffer *buf.Buffer, addr M.Socksaddr) error {
  134. return w.writer.WritePacket(buffer, w.source)
  135. }
  136. func (w *directPacketWriter) CreatePacketBatchWriter() (N.PacketBatchWriter, bool) {
  137. writer, created := bufio.CreatePacketBatchWriter(w.writer)
  138. if !created {
  139. return nil, false
  140. }
  141. return &directPacketBatchWriter{
  142. writer: writer,
  143. source: w.source,
  144. }, true
  145. }
  146. type directPacketBatchWriter struct {
  147. writer N.PacketBatchWriter
  148. source M.Socksaddr
  149. }
  150. func (w *directPacketBatchWriter) WritePacketBatch(buffers []*buf.Buffer, destinations []M.Socksaddr) error {
  151. if len(buffers) == 0 || len(buffers) != len(destinations) {
  152. buf.ReleaseMulti(buffers)
  153. return os.ErrInvalid
  154. }
  155. sources := make([]M.Socksaddr, len(destinations))
  156. for index := range sources {
  157. sources[index] = w.source
  158. }
  159. return w.writer.WritePacketBatch(buffers, sources)
  160. }