inbound.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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.NewServerWithOptions(tls.ServerOptions{
  44. Context: ctx,
  45. Logger: logger,
  46. Options: common.PtrValueOrDefault(options.TLS),
  47. KTLSCompatible: true,
  48. })
  49. if err != nil {
  50. return nil, err
  51. }
  52. inbound.tlsConfig = tlsConfig
  53. }
  54. inbound.listener = listener.New(listener.Options{
  55. Context: ctx,
  56. Logger: logger,
  57. Network: []string{N.NetworkTCP},
  58. Listen: options.ListenOptions,
  59. ConnectionHandler: inbound,
  60. SetSystemProxy: options.SetSystemProxy,
  61. SystemProxySOCKS: true,
  62. })
  63. return inbound, nil
  64. }
  65. func (h *Inbound) Start(stage adapter.StartStage) error {
  66. if stage != adapter.StartStateStart {
  67. return nil
  68. }
  69. if h.tlsConfig != nil {
  70. err := h.tlsConfig.Start()
  71. if err != nil {
  72. return E.Cause(err, "create TLS config")
  73. }
  74. }
  75. return h.listener.Start()
  76. }
  77. func (h *Inbound) Close() error {
  78. return common.Close(
  79. h.listener,
  80. h.tlsConfig,
  81. )
  82. }
  83. func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  84. err := h.newConnection(ctx, conn, metadata, onClose)
  85. N.CloseOnHandshakeFailure(conn, onClose, err)
  86. if err != nil {
  87. if E.IsClosedOrCanceled(err) {
  88. h.logger.DebugContext(ctx, "connection closed: ", err)
  89. } else {
  90. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
  91. }
  92. }
  93. }
  94. func (h *Inbound) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) error {
  95. if h.tlsConfig != nil {
  96. tlsConn, err := tls.ServerHandshake(ctx, conn, h.tlsConfig)
  97. if err != nil {
  98. return E.Cause(err, "TLS handshake")
  99. }
  100. conn = tlsConn
  101. }
  102. reader := std_bufio.NewReader(conn)
  103. headerBytes, err := reader.Peek(1)
  104. if err != nil {
  105. return E.Cause(err, "peek first byte")
  106. }
  107. switch headerBytes[0] {
  108. case socks4.Version, socks5.Version:
  109. return socks.HandleConnectionEx(ctx, conn, reader, h.authenticator, adapter.NewUpstreamHandlerEx(metadata, h.newUserConnection, h.streamUserPacketConnection), h.listener, metadata.Source, onClose)
  110. default:
  111. return http.HandleConnectionEx(ctx, conn, reader, h.authenticator, adapter.NewUpstreamHandlerEx(metadata, h.newUserConnection, h.streamUserPacketConnection), metadata.Source, onClose)
  112. }
  113. }
  114. func (h *Inbound) newUserConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  115. metadata.Inbound = h.Tag()
  116. metadata.InboundType = h.Type()
  117. user, loaded := auth.UserFromContext[string](ctx)
  118. if !loaded {
  119. h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  120. h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  121. return
  122. }
  123. metadata.User = user
  124. h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination)
  125. h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  126. }
  127. func (h *Inbound) streamUserPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  128. metadata.Inbound = h.Tag()
  129. metadata.InboundType = h.Type()
  130. user, loaded := auth.UserFromContext[string](ctx)
  131. if !loaded {
  132. if !metadata.Destination.IsValid() {
  133. h.logger.InfoContext(ctx, "inbound packet connection")
  134. } else {
  135. h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  136. }
  137. h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  138. return
  139. }
  140. metadata.User = user
  141. if !metadata.Destination.IsValid() {
  142. h.logger.InfoContext(ctx, "[", user, "] inbound packet connection")
  143. } else {
  144. h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination)
  145. }
  146. h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  147. }