default.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package inbound
  2. import (
  3. "context"
  4. "net"
  5. "github.com/sagernet/sing-box/adapter"
  6. "github.com/sagernet/sing-box/common/settings"
  7. C "github.com/sagernet/sing-box/constant"
  8. "github.com/sagernet/sing-box/log"
  9. "github.com/sagernet/sing-box/option"
  10. "github.com/sagernet/sing/common"
  11. "github.com/sagernet/sing/common/atomic"
  12. E "github.com/sagernet/sing/common/exceptions"
  13. M "github.com/sagernet/sing/common/metadata"
  14. N "github.com/sagernet/sing/common/network"
  15. )
  16. var _ adapter.Inbound = (*myInboundAdapter)(nil)
  17. type myInboundAdapter struct {
  18. protocol string
  19. network []string
  20. ctx context.Context
  21. router adapter.ConnectionRouterEx
  22. logger log.ContextLogger
  23. tag string
  24. listenOptions option.ListenOptions
  25. connHandler adapter.ConnectionHandlerEx
  26. packetHandler adapter.PacketHandlerEx
  27. oobPacketHandler adapter.OOBPacketHandlerEx
  28. packetUpstream any
  29. // http mixed
  30. setSystemProxy bool
  31. systemProxy settings.SystemProxy
  32. // internal
  33. tcpListener net.Listener
  34. udpConn *net.UDPConn
  35. udpAddr M.Socksaddr
  36. packetOutboundClosed chan struct{}
  37. packetOutbound chan *myInboundPacket
  38. inShutdown atomic.Bool
  39. }
  40. func (a *myInboundAdapter) Type() string {
  41. return a.protocol
  42. }
  43. func (a *myInboundAdapter) Tag() string {
  44. return a.tag
  45. }
  46. func (a *myInboundAdapter) Start() error {
  47. var err error
  48. if common.Contains(a.network, N.NetworkTCP) {
  49. _, err = a.ListenTCP()
  50. if err != nil {
  51. return err
  52. }
  53. go a.loopTCPIn()
  54. }
  55. if common.Contains(a.network, N.NetworkUDP) {
  56. _, err = a.ListenUDP()
  57. if err != nil {
  58. return err
  59. }
  60. a.packetOutboundClosed = make(chan struct{})
  61. a.packetOutbound = make(chan *myInboundPacket)
  62. if a.oobPacketHandler != nil {
  63. if _, threadUnsafeHandler := common.Cast[N.ThreadUnsafeWriter](a.packetUpstream); !threadUnsafeHandler {
  64. go a.loopUDPOOBIn()
  65. } else {
  66. go a.loopUDPOOBInThreadSafe()
  67. }
  68. } else {
  69. if _, threadUnsafeHandler := common.Cast[N.ThreadUnsafeWriter](a.packetUpstream); !threadUnsafeHandler {
  70. go a.loopUDPIn()
  71. } else {
  72. go a.loopUDPInThreadSafe()
  73. }
  74. go a.loopUDPOut()
  75. }
  76. }
  77. if a.setSystemProxy {
  78. listenPort := M.SocksaddrFromNet(a.tcpListener.Addr()).Port
  79. var listenAddrString string
  80. listenAddr := a.listenOptions.Listen.Build()
  81. if listenAddr.IsUnspecified() {
  82. listenAddrString = "127.0.0.1"
  83. } else {
  84. listenAddrString = listenAddr.String()
  85. }
  86. var systemProxy settings.SystemProxy
  87. systemProxy, err = settings.NewSystemProxy(a.ctx, M.ParseSocksaddrHostPort(listenAddrString, listenPort), a.protocol == C.TypeMixed)
  88. if err != nil {
  89. return E.Cause(err, "initialize system proxy")
  90. }
  91. err = systemProxy.Enable()
  92. if err != nil {
  93. return E.Cause(err, "set system proxy")
  94. }
  95. a.systemProxy = systemProxy
  96. }
  97. return nil
  98. }
  99. func (a *myInboundAdapter) Close() error {
  100. a.inShutdown.Store(true)
  101. var err error
  102. if a.systemProxy != nil && a.systemProxy.IsEnabled() {
  103. err = a.systemProxy.Disable()
  104. }
  105. return E.Errors(err, common.Close(
  106. a.tcpListener,
  107. common.PtrOrNil(a.udpConn),
  108. ))
  109. }
  110. func (a *myInboundAdapter) upstreamHandler(metadata adapter.InboundContext) adapter.UpstreamHandlerAdapter {
  111. return adapter.NewUpstreamHandler(metadata, a.newConnection, a.streamPacketConnection, a)
  112. }
  113. func (a *myInboundAdapter) upstreamContextHandler() adapter.UpstreamHandlerAdapter {
  114. return adapter.NewUpstreamContextHandler(a.newConnection, a.newPacketConnection, a)
  115. }
  116. func (a *myInboundAdapter) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  117. a.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  118. return a.router.RouteConnection(ctx, conn, metadata)
  119. }
  120. func (a *myInboundAdapter) streamPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  121. a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  122. return a.router.RoutePacketConnection(ctx, conn, metadata)
  123. }
  124. func (a *myInboundAdapter) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  125. ctx = log.ContextWithNewID(ctx)
  126. a.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  127. a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  128. return a.router.RoutePacketConnection(ctx, conn, metadata)
  129. }
  130. func (a *myInboundAdapter) upstreamHandlerEx(metadata adapter.InboundContext) adapter.UpstreamHandlerAdapterEx {
  131. return adapter.NewUpstreamHandlerEx(metadata, a.newConnectionEx, a.streamPacketConnectionEx)
  132. }
  133. func (a *myInboundAdapter) upstreamContextHandlerEx() adapter.UpstreamHandlerAdapterEx {
  134. return adapter.NewUpstreamContextHandlerEx(a.newConnectionEx, a.newPacketConnectionEx)
  135. }
  136. func (a *myInboundAdapter) newConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  137. a.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  138. a.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  139. }
  140. func (a *myInboundAdapter) newPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  141. ctx = log.ContextWithNewID(ctx)
  142. a.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  143. a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  144. a.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  145. }
  146. func (a *myInboundAdapter) streamPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  147. a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  148. a.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  149. }
  150. func (a *myInboundAdapter) createMetadata(conn net.Conn, metadata adapter.InboundContext) adapter.InboundContext {
  151. metadata.Inbound = a.tag
  152. metadata.InboundType = a.protocol
  153. metadata.InboundDetour = a.listenOptions.Detour
  154. metadata.InboundOptions = a.listenOptions.InboundOptions
  155. if !metadata.Source.IsValid() {
  156. metadata.Source = M.SocksaddrFromNet(conn.RemoteAddr()).Unwrap()
  157. }
  158. if !metadata.Destination.IsValid() {
  159. metadata.Destination = M.SocksaddrFromNet(conn.LocalAddr()).Unwrap()
  160. }
  161. if tcpConn, isTCP := common.Cast[*net.TCPConn](conn); isTCP {
  162. metadata.OriginDestination = M.SocksaddrFromNet(tcpConn.LocalAddr()).Unwrap()
  163. }
  164. return metadata
  165. }
  166. // Deprecated: don't use
  167. func (a *myInboundAdapter) newError(err error) {
  168. a.logger.Error(err)
  169. }
  170. // Deprecated: don't use
  171. func (a *myInboundAdapter) NewError(ctx context.Context, err error) {
  172. NewError(a.logger, ctx, err)
  173. }
  174. // Deprecated: don't use
  175. func NewError(logger log.ContextLogger, ctx context.Context, err error) {
  176. common.Close(err)
  177. if E.IsClosedOrCanceled(err) {
  178. logger.DebugContext(ctx, "connection closed: ", err)
  179. return
  180. }
  181. logger.ErrorContext(ctx, err)
  182. }