inbound.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package shadowsocks
  2. import (
  3. "context"
  4. "net"
  5. "time"
  6. "github.com/sagernet/sing-box/adapter"
  7. "github.com/sagernet/sing-box/adapter/inbound"
  8. "github.com/sagernet/sing-box/common/listener"
  9. "github.com/sagernet/sing-box/common/mux"
  10. "github.com/sagernet/sing-box/common/uot"
  11. C "github.com/sagernet/sing-box/constant"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. "github.com/sagernet/sing-shadowsocks"
  15. "github.com/sagernet/sing-shadowsocks/shadowaead"
  16. "github.com/sagernet/sing-shadowsocks/shadowaead_2022"
  17. "github.com/sagernet/sing/common"
  18. "github.com/sagernet/sing/common/buf"
  19. E "github.com/sagernet/sing/common/exceptions"
  20. "github.com/sagernet/sing/common/logger"
  21. M "github.com/sagernet/sing/common/metadata"
  22. N "github.com/sagernet/sing/common/network"
  23. "github.com/sagernet/sing/common/ntp"
  24. )
  25. func RegisterInbound(registry *inbound.Registry) {
  26. inbound.Register[option.ShadowsocksInboundOptions](registry, C.TypeShadowsocks, NewInbound)
  27. }
  28. func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (adapter.Inbound, error) {
  29. if len(options.Users) > 0 && len(options.Destinations) > 0 {
  30. return nil, E.New("users and destinations options must not be combined")
  31. } else if options.Managed && (len(options.Users) > 0 || len(options.Destinations) > 0) {
  32. return nil, E.New("users and destinations options are not supported in managed servers")
  33. }
  34. if len(options.Users) > 0 || options.Managed {
  35. return newMultiInbound(ctx, router, logger, tag, options)
  36. } else if len(options.Destinations) > 0 {
  37. return newRelayInbound(ctx, router, logger, tag, options)
  38. } else {
  39. return newInbound(ctx, router, logger, tag, options)
  40. }
  41. }
  42. var _ adapter.TCPInjectableInbound = (*Inbound)(nil)
  43. type Inbound struct {
  44. inbound.Adapter
  45. ctx context.Context
  46. router adapter.ConnectionRouterEx
  47. logger logger.ContextLogger
  48. listener *listener.Listener
  49. service shadowsocks.Service
  50. }
  51. func newInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (*Inbound, error) {
  52. inbound := &Inbound{
  53. Adapter: inbound.NewAdapter(C.TypeShadowsocks, tag),
  54. ctx: ctx,
  55. router: uot.NewRouter(router, logger),
  56. logger: logger,
  57. }
  58. var err error
  59. inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex))
  60. if err != nil {
  61. return nil, err
  62. }
  63. var udpTimeout time.Duration
  64. if options.UDPTimeout != 0 {
  65. udpTimeout = time.Duration(options.UDPTimeout)
  66. } else {
  67. udpTimeout = C.UDPTimeout
  68. }
  69. switch {
  70. case options.Method == shadowsocks.MethodNone:
  71. inbound.service = shadowsocks.NewNoneService(int64(udpTimeout.Seconds()), adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, inbound))
  72. case common.Contains(shadowaead.List, options.Method):
  73. inbound.service, err = shadowaead.NewService(options.Method, nil, options.Password, int64(udpTimeout.Seconds()), adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, inbound))
  74. case common.Contains(shadowaead_2022.List, options.Method):
  75. inbound.service, err = shadowaead_2022.NewServiceWithPassword(options.Method, options.Password, int64(udpTimeout.Seconds()), adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, inbound), ntp.TimeFuncFromContext(ctx))
  76. default:
  77. err = E.New("unsupported method: ", options.Method)
  78. }
  79. inbound.listener = listener.New(listener.Options{
  80. Context: ctx,
  81. Logger: logger,
  82. Network: options.Network.Build(),
  83. Listen: options.ListenOptions,
  84. ConnectionHandler: inbound,
  85. PacketHandler: inbound,
  86. ThreadUnsafePacketWriter: true,
  87. })
  88. return inbound, err
  89. }
  90. func (h *Inbound) Start(stage adapter.StartStage) error {
  91. if stage != adapter.StartStateStart {
  92. return nil
  93. }
  94. return h.listener.Start()
  95. }
  96. func (h *Inbound) Close() error {
  97. return h.listener.Close()
  98. }
  99. //nolint:staticcheck
  100. func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  101. err := h.service.NewConnection(ctx, conn, adapter.UpstreamMetadata(metadata))
  102. N.CloseOnHandshakeFailure(conn, onClose, err)
  103. if err != nil {
  104. if E.IsClosedOrCanceled(err) {
  105. h.logger.DebugContext(ctx, "connection closed: ", err)
  106. } else {
  107. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
  108. }
  109. }
  110. }
  111. //nolint:staticcheck
  112. func (h *Inbound) NewPacketEx(buffer *buf.Buffer, source M.Socksaddr) {
  113. err := h.service.NewPacket(h.ctx, &stubPacketConn{h.listener.PacketWriter()}, buffer, M.Metadata{Source: source})
  114. if err != nil {
  115. h.logger.Error(E.Cause(err, "process packet from ", source))
  116. }
  117. }
  118. func (h *Inbound) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  119. h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  120. metadata.Inbound = h.Tag()
  121. metadata.InboundType = h.Type()
  122. return h.router.RouteConnection(ctx, conn, metadata)
  123. }
  124. func (h *Inbound) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  125. ctx = log.ContextWithNewID(ctx)
  126. h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source)
  127. h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  128. metadata.Inbound = h.Tag()
  129. metadata.InboundType = h.Type()
  130. return h.router.RoutePacketConnection(ctx, conn, metadata)
  131. }
  132. var _ N.PacketConn = (*stubPacketConn)(nil)
  133. type stubPacketConn struct {
  134. N.PacketWriter
  135. }
  136. func (c *stubPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
  137. panic("stub!")
  138. }
  139. func (c *stubPacketConn) Close() error {
  140. return nil
  141. }
  142. func (c *stubPacketConn) LocalAddr() net.Addr {
  143. panic("stub!")
  144. }
  145. func (c *stubPacketConn) SetDeadline(t time.Time) error {
  146. panic("stub!")
  147. }
  148. func (c *stubPacketConn) SetReadDeadline(t time.Time) error {
  149. panic("stub!")
  150. }
  151. func (c *stubPacketConn) SetWriteDeadline(t time.Time) error {
  152. panic("stub!")
  153. }
  154. func (h *Inbound) NewError(ctx context.Context, err error) {
  155. NewError(h.logger, ctx, err)
  156. }
  157. // Deprecated: remove
  158. func NewError(logger logger.ContextLogger, ctx context.Context, err error) {
  159. common.Close(err)
  160. if E.IsClosedOrCanceled(err) {
  161. logger.DebugContext(ctx, "connection closed: ", err)
  162. return
  163. }
  164. logger.ErrorContext(ctx, err)
  165. }