inbound.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package vmess
  2. import (
  3. "context"
  4. "net"
  5. "os"
  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/tls"
  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-box/transport/v2ray"
  16. "github.com/sagernet/sing-vmess"
  17. "github.com/sagernet/sing-vmess/packetaddr"
  18. "github.com/sagernet/sing/common"
  19. "github.com/sagernet/sing/common/auth"
  20. "github.com/sagernet/sing/common/bufio"
  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. func RegisterInbound(registry *inbound.Registry) {
  29. inbound.Register[option.VMessInboundOptions](registry, C.TypeVMess, NewInbound)
  30. }
  31. var _ adapter.TCPInjectableInbound = (*Inbound)(nil)
  32. type Inbound struct {
  33. inbound.Adapter
  34. ctx context.Context
  35. router adapter.ConnectionRouterEx
  36. logger logger.ContextLogger
  37. listener *listener.Listener
  38. service *vmess.Service[int]
  39. users []option.VMessUser
  40. tlsConfig tls.ServerConfig
  41. transport adapter.V2RayServerTransport
  42. }
  43. func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.VMessInboundOptions) (adapter.Inbound, error) {
  44. inbound := &Inbound{
  45. Adapter: inbound.NewAdapter(C.TypeVMess, tag),
  46. ctx: ctx,
  47. router: uot.NewRouter(router, logger),
  48. logger: logger,
  49. users: options.Users,
  50. }
  51. var err error
  52. inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex))
  53. if err != nil {
  54. return nil, err
  55. }
  56. var serviceOptions []vmess.ServiceOption
  57. if timeFunc := ntp.TimeFuncFromContext(ctx); timeFunc != nil {
  58. serviceOptions = append(serviceOptions, vmess.ServiceWithTimeFunc(timeFunc))
  59. }
  60. if options.Transport != nil && options.Transport.Type != "" {
  61. serviceOptions = append(serviceOptions, vmess.ServiceWithDisableHeaderProtection())
  62. }
  63. service := vmess.NewService[int](adapter.NewUpstreamContextHandlerEx(inbound.newConnectionEx, inbound.newPacketConnectionEx), serviceOptions...)
  64. inbound.service = service
  65. err = service.UpdateUsers(common.MapIndexed(options.Users, func(index int, it option.VMessUser) int {
  66. return index
  67. }), common.Map(options.Users, func(it option.VMessUser) string {
  68. return it.UUID
  69. }), common.Map(options.Users, func(it option.VMessUser) int {
  70. return it.AlterId
  71. }))
  72. if err != nil {
  73. return nil, err
  74. }
  75. if options.TLS != nil {
  76. inbound.tlsConfig, err = tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS))
  77. if err != nil {
  78. return nil, err
  79. }
  80. }
  81. if options.Transport != nil {
  82. inbound.transport, err = v2ray.NewServerTransport(ctx, logger, common.PtrValueOrDefault(options.Transport), inbound.tlsConfig, (*inboundTransportHandler)(inbound))
  83. if err != nil {
  84. return nil, E.Cause(err, "create server transport: ", options.Transport.Type)
  85. }
  86. }
  87. inbound.listener = listener.New(listener.Options{
  88. Context: ctx,
  89. Logger: logger,
  90. Network: []string{N.NetworkTCP},
  91. Listen: options.ListenOptions,
  92. ConnectionHandler: inbound,
  93. })
  94. return inbound, nil
  95. }
  96. func (h *Inbound) Start(stage adapter.StartStage) error {
  97. if stage != adapter.StartStateStart {
  98. return nil
  99. }
  100. err := h.service.Start()
  101. if err != nil {
  102. return err
  103. }
  104. if h.tlsConfig != nil {
  105. err = h.tlsConfig.Start()
  106. if err != nil {
  107. return err
  108. }
  109. }
  110. if h.transport == nil {
  111. return h.listener.Start()
  112. }
  113. if common.Contains(h.transport.Network(), N.NetworkTCP) {
  114. tcpListener, err := h.listener.ListenTCP()
  115. if err != nil {
  116. return err
  117. }
  118. go func() {
  119. sErr := h.transport.Serve(tcpListener)
  120. if sErr != nil && !E.IsClosed(sErr) {
  121. h.logger.Error("transport serve error: ", sErr)
  122. }
  123. }()
  124. }
  125. if common.Contains(h.transport.Network(), N.NetworkUDP) {
  126. udpConn, err := h.listener.ListenUDP()
  127. if err != nil {
  128. return err
  129. }
  130. go func() {
  131. sErr := h.transport.ServePacket(udpConn)
  132. if sErr != nil && !E.IsClosed(sErr) {
  133. h.logger.Error("transport serve error: ", sErr)
  134. }
  135. }()
  136. }
  137. return nil
  138. }
  139. func (h *Inbound) Close() error {
  140. return common.Close(
  141. h.service,
  142. h.listener,
  143. h.tlsConfig,
  144. h.transport,
  145. )
  146. }
  147. func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  148. if h.tlsConfig != nil && h.transport == nil {
  149. tlsConn, err := tls.ServerHandshake(ctx, conn, h.tlsConfig)
  150. if err != nil {
  151. N.CloseOnHandshakeFailure(conn, onClose, err)
  152. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source, ": TLS handshake"))
  153. return
  154. }
  155. conn = tlsConn
  156. }
  157. err := h.service.NewConnection(adapter.WithContext(ctx, &metadata), conn, metadata.Source, onClose)
  158. if err != nil {
  159. N.CloseOnHandshakeFailure(conn, onClose, err)
  160. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
  161. }
  162. }
  163. func (h *Inbound) newConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  164. metadata.Inbound = h.Tag()
  165. metadata.InboundType = h.Type()
  166. userIndex, loaded := auth.UserFromContext[int](ctx)
  167. if !loaded {
  168. N.CloseOnHandshakeFailure(conn, onClose, os.ErrInvalid)
  169. return
  170. }
  171. user := h.users[userIndex].Name
  172. if user == "" {
  173. user = F.ToString(userIndex)
  174. } else {
  175. metadata.User = user
  176. }
  177. h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination)
  178. h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
  179. }
  180. func (h *Inbound) newPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  181. metadata.Inbound = h.Tag()
  182. metadata.InboundType = h.Type()
  183. userIndex, loaded := auth.UserFromContext[int](ctx)
  184. if !loaded {
  185. N.CloseOnHandshakeFailure(conn, onClose, os.ErrInvalid)
  186. return
  187. }
  188. user := h.users[userIndex].Name
  189. if user == "" {
  190. user = F.ToString(userIndex)
  191. } else {
  192. metadata.User = user
  193. }
  194. if metadata.Destination.Fqdn == packetaddr.SeqPacketMagicAddress {
  195. metadata.Destination = M.Socksaddr{}
  196. conn = packetaddr.NewConn(bufio.NewNetPacketConn(conn), metadata.Destination)
  197. h.logger.InfoContext(ctx, "[", user, "] inbound packet addr connection")
  198. } else {
  199. h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination)
  200. }
  201. h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
  202. }
  203. var _ adapter.V2RayServerTransportHandler = (*inboundTransportHandler)(nil)
  204. type inboundTransportHandler Inbound
  205. func (h *inboundTransportHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
  206. var metadata adapter.InboundContext
  207. metadata.Source = source
  208. metadata.Destination = destination
  209. //nolint:staticcheck
  210. metadata.InboundDetour = h.listener.ListenOptions().Detour
  211. //nolint:staticcheck
  212. metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
  213. h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
  214. (*Inbound)(h).NewConnectionEx(ctx, conn, metadata, onClose)
  215. }