1
0

inbound_multi.go 5.9 KB

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