inbound.go 6.2 KB

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