inbound_relay.go 5.1 KB

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