1
0

inbound.go 7.1 KB

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