inbound.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package mixed
  2. import (
  3. std_bufio "bufio"
  4. "context"
  5. "net"
  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/tls"
  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/common"
  15. "github.com/sagernet/sing/common/auth"
  16. E "github.com/sagernet/sing/common/exceptions"
  17. N "github.com/sagernet/sing/common/network"
  18. "github.com/sagernet/sing/protocol/http"
  19. "github.com/sagernet/sing/protocol/socks"
  20. "github.com/sagernet/sing/protocol/socks/socks4"
  21. "github.com/sagernet/sing/protocol/socks/socks5"
  22. )
  23. func RegisterInbound(registry *inbound.Registry) {
  24. inbound.Register[option.HTTPMixedInboundOptions](registry, C.TypeMixed, NewInbound)
  25. }
  26. var _ adapter.TCPInjectableInbound = (*Inbound)(nil)
  27. type Inbound struct {
  28. inbound.Adapter
  29. router adapter.ConnectionRouterEx
  30. logger log.ContextLogger
  31. listener *listener.Listener
  32. authenticator *auth.Authenticator
  33. tlsConfig tls.ServerConfig
  34. }
  35. func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPMixedInboundOptions) (adapter.Inbound, error) {
  36. inbound := &Inbound{
  37. Adapter: inbound.NewAdapter(C.TypeMixed, tag),
  38. router: uot.NewRouter(router, logger),
  39. logger: logger,
  40. authenticator: auth.NewAuthenticator(options.Users),
  41. }
  42. if options.TLS != nil {
  43. tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS))
  44. if err != nil {
  45. return nil, err
  46. }
  47. inbound.tlsConfig = tlsConfig
  48. }
  49. inbound.listener = listener.New(listener.Options{
  50. Context: ctx,
  51. Logger: logger,
  52. Network: []string{N.NetworkTCP},
  53. Listen: options.ListenOptions,
  54. ConnectionHandler: inbound,
  55. SetSystemProxy: options.SetSystemProxy,
  56. SystemProxySOCKS: true,
  57. })
  58. return inbound, nil
  59. }
  60. func (h *Inbound) Start(stage adapter.StartStage) error {
  61. if stage != adapter.StartStateStart {
  62. return nil
  63. }
  64. if h.tlsConfig != nil {
  65. err := h.tlsConfig.Start()
  66. if err != nil {
  67. return E.Cause(err, "create TLS config")
  68. }
  69. }
  70. return h.listener.Start()
  71. }
  72. func (h *Inbound) Close() error {
  73. return common.Close(
  74. h.listener,
  75. h.tlsConfig,
  76. )
  77. }
  78. func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  79. err := h.newConnection(ctx, conn, metadata, onClose)
  80. N.CloseOnHandshakeFailure(conn, onClose, err)
  81. if err != nil {
  82. if E.IsClosedOrCanceled(err) {
  83. h.logger.DebugContext(ctx, "connection closed: ", err)
  84. } else {
  85. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
  86. }
  87. }
  88. }
  89. func (h *Inbound) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
  90. if h.tlsConfig != nil {
  91. tlsConn, err := tls.ServerHandshake(ctx, conn, h.tlsConfig)
  92. if err != nil {
  93. return E.Cause(err, "TLS handshake")
  94. }
  95. conn = tlsConn
  96. }
  97. reader := std_bufio.NewReader(conn)
  98. headerBytes, err := reader.Peek(1)
  99. if err != nil {
  100. return E.Cause(err, "peek first byte")
  101. }
  102. switch headerBytes[0] {
  103. case socks4.Version, socks5.Version:
  104. return socks.HandleConnectionEx(ctx, conn, reader, h.authenticator, adapter.NewUpstreamHandlerEx(metadata, h.newUserConnection, h.streamUserPacketConnection), h.listener, metadata.Source, onClose)
  105. default:
  106. return http.HandleConnectionEx(ctx, conn, reader, h.authenticator, adapter.NewUpstreamHandlerEx(metadata, h.newUserConnection, h.streamUserPacketConnection), metadata.Source, onClose)
  107. }
  108. }
  109. func (h *Inbound) newUserConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  110. metadata.Inbound = h.Tag()
  111. metadata.InboundType = h.Type()
  112. user, loaded := auth.UserFromContext[string](ctx)
  113. if !loaded {
  114. h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  115. h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  116. return
  117. }
  118. metadata.User = user
  119. h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination)
  120. h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  121. }
  122. func (h *Inbound) streamUserPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  123. metadata.Inbound = h.Tag()
  124. metadata.InboundType = h.Type()
  125. user, loaded := auth.UserFromContext[string](ctx)
  126. if !loaded {
  127. if !metadata.Destination.IsValid() {
  128. h.logger.InfoContext(ctx, "inbound packet connection")
  129. } else {
  130. h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  131. }
  132. h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  133. return
  134. }
  135. metadata.User = user
  136. if !metadata.Destination.IsValid() {
  137. h.logger.InfoContext(ctx, "[", user, "] inbound packet connection")
  138. } else {
  139. h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination)
  140. }
  141. h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  142. }