1
0

inbound_relay.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. package shadowsocks
  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. "github.com/sagernet/sing-box/common/mux"
  11. "github.com/sagernet/sing-box/common/uot"
  12. C "github.com/sagernet/sing-box/constant"
  13. "github.com/sagernet/sing-box/log"
  14. "github.com/sagernet/sing-box/option"
  15. "github.com/sagernet/sing-shadowsocks/shadowaead_2022"
  16. "github.com/sagernet/sing/common"
  17. "github.com/sagernet/sing/common/auth"
  18. "github.com/sagernet/sing/common/buf"
  19. E "github.com/sagernet/sing/common/exceptions"
  20. F "github.com/sagernet/sing/common/format"
  21. "github.com/sagernet/sing/common/logger"
  22. M "github.com/sagernet/sing/common/metadata"
  23. N "github.com/sagernet/sing/common/network"
  24. )
  25. var _ adapter.TCPInjectableInbound = (*RelayInbound)(nil)
  26. type RelayInbound struct {
  27. inbound.Adapter
  28. ctx context.Context
  29. router adapter.ConnectionRouterEx
  30. logger logger.ContextLogger
  31. listener *listener.Listener
  32. service *shadowaead_2022.RelayService[int]
  33. destinations []option.ShadowsocksDestination
  34. }
  35. func newRelayInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (*RelayInbound, error) {
  36. inbound := &RelayInbound{
  37. Adapter: inbound.NewAdapter(C.TypeShadowsocks, tag),
  38. ctx: ctx,
  39. router: uot.NewRouter(router, logger),
  40. logger: logger,
  41. destinations: options.Destinations,
  42. }
  43. var err error
  44. inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex))
  45. if err != nil {
  46. return nil, err
  47. }
  48. var udpTimeout time.Duration
  49. if options.UDPTimeout != 0 {
  50. udpTimeout = time.Duration(options.UDPTimeout)
  51. } else {
  52. udpTimeout = C.UDPTimeout
  53. }
  54. service, err := shadowaead_2022.NewRelayServiceWithPassword[int](
  55. options.Method,
  56. options.Password,
  57. int64(udpTimeout.Seconds()),
  58. adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, inbound),
  59. )
  60. if err != nil {
  61. return nil, err
  62. }
  63. err = service.UpdateUsersWithPasswords(common.MapIndexed(options.Destinations, func(index int, user option.ShadowsocksDestination) int {
  64. return index
  65. }), common.Map(options.Destinations, func(user option.ShadowsocksDestination) string {
  66. return user.Password
  67. }), common.Map(options.Destinations, option.ShadowsocksDestination.Build))
  68. if err != nil {
  69. return nil, err
  70. }
  71. inbound.service = service
  72. inbound.listener = listener.New(listener.Options{
  73. Context: ctx,
  74. Logger: logger,
  75. Network: options.Network.Build(),
  76. Listen: options.ListenOptions,
  77. ConnectionHandler: inbound,
  78. PacketHandler: inbound,
  79. ThreadUnsafePacketWriter: true,
  80. })
  81. return inbound, err
  82. }
  83. func (h *RelayInbound) Start(stage adapter.StartStage) error {
  84. if stage != adapter.StartStateStart {
  85. return nil
  86. }
  87. return h.listener.Start()
  88. }
  89. func (h *RelayInbound) Close() error {
  90. return h.listener.Close()
  91. }
  92. //nolint:staticcheck
  93. func (h *RelayInbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  94. err := h.service.NewConnection(ctx, conn, adapter.UpstreamMetadata(metadata))
  95. N.CloseOnHandshakeFailure(conn, onClose, err)
  96. if err != nil {
  97. if E.IsClosedOrCanceled(err) {
  98. h.logger.DebugContext(ctx, "connection closed: ", err)
  99. } else {
  100. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
  101. }
  102. }
  103. }
  104. //nolint:staticcheck
  105. func (h *RelayInbound) NewPacketEx(buffer *buf.Buffer, source M.Socksaddr) {
  106. err := h.service.NewPacket(h.ctx, &stubPacketConn{h.listener.PacketWriter()}, buffer, M.Metadata{Source: source})
  107. if err != nil {
  108. h.logger.Error(E.Cause(err, "process packet from ", source))
  109. }
  110. }
  111. func (h *RelayInbound) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  112. destinationIndex, loaded := auth.UserFromContext[int](ctx)
  113. if !loaded {
  114. return os.ErrInvalid
  115. }
  116. destination := h.destinations[destinationIndex].Name
  117. if destination == "" {
  118. destination = F.ToString(destinationIndex)
  119. } else {
  120. metadata.User = destination
  121. }
  122. h.logger.InfoContext(ctx, "[", destination, "] inbound connection to ", metadata.Destination)
  123. metadata.Inbound = h.Tag()
  124. metadata.InboundType = h.Type()
  125. //nolint:staticcheck
  126. metadata.InboundDetour = h.listener.ListenOptions().Detour
  127. //nolint:staticcheck
  128. metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
  129. return h.router.RouteConnection(ctx, conn, metadata)
  130. }
  131. func (h *RelayInbound) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  132. destinationIndex, loaded := auth.UserFromContext[int](ctx)
  133. if !loaded {
  134. return os.ErrInvalid
  135. }
  136. destination := h.destinations[destinationIndex].Name
  137. if destination == "" {
  138. destination = F.ToString(destinationIndex)
  139. } else {
  140. metadata.User = destination
  141. }
  142. ctx = log.ContextWithNewID(ctx)
  143. h.logger.InfoContext(ctx, "[", destination, "] inbound packet connection from ", metadata.Source)
  144. h.logger.InfoContext(ctx, "[", destination, "] inbound packet connection to ", metadata.Destination)
  145. metadata.Inbound = h.Tag()
  146. metadata.InboundType = h.Type()
  147. //nolint:staticcheck
  148. metadata.InboundDetour = h.listener.ListenOptions().Detour
  149. //nolint:staticcheck
  150. metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
  151. return h.router.RoutePacketConnection(ctx, conn, metadata)
  152. }
  153. //nolint:staticcheck
  154. func (h *RelayInbound) NewError(ctx context.Context, err error) {
  155. NewError(h.logger, ctx, err)
  156. }