inbound_relay.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. func (h *RelayInbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  93. err := h.service.NewConnection(ctx, conn, adapter.UpstreamMetadata(metadata))
  94. N.CloseOnHandshakeFailure(conn, onClose, err)
  95. if err != nil {
  96. if E.IsClosedOrCanceled(err) {
  97. h.logger.DebugContext(ctx, "connection closed: ", err)
  98. } else {
  99. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
  100. }
  101. }
  102. }
  103. func (h *RelayInbound) NewPacketEx(buffer *buf.Buffer, source M.Socksaddr) {
  104. err := h.service.NewPacket(h.ctx, &stubPacketConn{h.listener.PacketWriter()}, buffer, M.Metadata{Source: source})
  105. if err != nil {
  106. h.logger.Error(E.Cause(err, "process packet from ", source))
  107. }
  108. }
  109. func (h *RelayInbound) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  110. destinationIndex, loaded := auth.UserFromContext[int](ctx)
  111. if !loaded {
  112. return os.ErrInvalid
  113. }
  114. destination := h.destinations[destinationIndex].Name
  115. if destination == "" {
  116. destination = F.ToString(destinationIndex)
  117. } else {
  118. metadata.User = destination
  119. }
  120. h.logger.InfoContext(ctx, "[", destination, "] inbound connection to ", metadata.Destination)
  121. metadata.Inbound = h.Tag()
  122. metadata.InboundType = h.Type()
  123. metadata.InboundDetour = h.listener.ListenOptions().Detour
  124. metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
  125. return h.router.RouteConnection(ctx, conn, metadata)
  126. }
  127. func (h *RelayInbound) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  128. destinationIndex, loaded := auth.UserFromContext[int](ctx)
  129. if !loaded {
  130. return os.ErrInvalid
  131. }
  132. destination := h.destinations[destinationIndex].Name
  133. if destination == "" {
  134. destination = F.ToString(destinationIndex)
  135. } else {
  136. metadata.User = destination
  137. }
  138. ctx = log.ContextWithNewID(ctx)
  139. h.logger.InfoContext(ctx, "[", destination, "] inbound packet connection from ", metadata.Source)
  140. h.logger.InfoContext(ctx, "[", destination, "] inbound packet connection to ", metadata.Destination)
  141. metadata.Inbound = h.Tag()
  142. metadata.InboundType = h.Type()
  143. metadata.InboundDetour = h.listener.ListenOptions().Detour
  144. metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
  145. return h.router.RoutePacketConnection(ctx, conn, metadata)
  146. }
  147. func (h *RelayInbound) NewError(ctx context.Context, err error) {
  148. NewError(h.logger, ctx, err)
  149. }