inbound.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package inbound
  2. import (
  3. "sync"
  4. "github.com/v2ray/v2ray-core/app"
  5. "github.com/v2ray/v2ray-core/app/dispatcher"
  6. "github.com/v2ray/v2ray-core/app/proxyman"
  7. v2io "github.com/v2ray/v2ray-core/common/io"
  8. "github.com/v2ray/v2ray-core/common/log"
  9. v2net "github.com/v2ray/v2ray-core/common/net"
  10. proto "github.com/v2ray/v2ray-core/common/protocol"
  11. raw "github.com/v2ray/v2ray-core/common/protocol/raw"
  12. "github.com/v2ray/v2ray-core/common/serial"
  13. "github.com/v2ray/v2ray-core/common/uuid"
  14. "github.com/v2ray/v2ray-core/proxy"
  15. "github.com/v2ray/v2ray-core/proxy/internal"
  16. vmessio "github.com/v2ray/v2ray-core/proxy/vmess/io"
  17. "github.com/v2ray/v2ray-core/proxy/vmess/protocol"
  18. "github.com/v2ray/v2ray-core/transport/hub"
  19. )
  20. type userByEmail struct {
  21. sync.RWMutex
  22. cache map[string]*proto.User
  23. defaultLevel proto.UserLevel
  24. defaultAlterIDs uint16
  25. }
  26. func NewUserByEmail(users []*proto.User, config *DefaultConfig) *userByEmail {
  27. cache := make(map[string]*proto.User)
  28. for _, user := range users {
  29. cache[user.Email] = user
  30. }
  31. return &userByEmail{
  32. cache: cache,
  33. defaultLevel: config.Level,
  34. defaultAlterIDs: config.AlterIDs,
  35. }
  36. }
  37. func (this *userByEmail) Get(email string) (*proto.User, bool) {
  38. var user *proto.User
  39. var found bool
  40. this.RLock()
  41. user, found = this.cache[email]
  42. this.RUnlock()
  43. if !found {
  44. this.Lock()
  45. user, found = this.cache[email]
  46. if !found {
  47. id := proto.NewID(uuid.New())
  48. user = proto.NewUser(id, this.defaultLevel, this.defaultAlterIDs, email)
  49. this.cache[email] = user
  50. }
  51. this.Unlock()
  52. }
  53. return user, found
  54. }
  55. // Inbound connection handler that handles messages in VMess format.
  56. type VMessInboundHandler struct {
  57. sync.Mutex
  58. packetDispatcher dispatcher.PacketDispatcher
  59. inboundHandlerManager proxyman.InboundHandlerManager
  60. clients proto.UserValidator
  61. usersByEmail *userByEmail
  62. accepting bool
  63. listener *hub.TCPHub
  64. features *FeaturesConfig
  65. listeningPort v2net.Port
  66. }
  67. func (this *VMessInboundHandler) Port() v2net.Port {
  68. return this.listeningPort
  69. }
  70. func (this *VMessInboundHandler) Close() {
  71. this.accepting = false
  72. if this.listener != nil {
  73. this.Lock()
  74. this.listener.Close()
  75. this.listener = nil
  76. this.Unlock()
  77. }
  78. }
  79. func (this *VMessInboundHandler) GetUser(email string) *proto.User {
  80. user, existing := this.usersByEmail.Get(email)
  81. if !existing {
  82. this.clients.Add(user)
  83. }
  84. return user
  85. }
  86. func (this *VMessInboundHandler) Listen(port v2net.Port) error {
  87. if this.accepting {
  88. if this.listeningPort == port {
  89. return nil
  90. } else {
  91. return proxy.ErrorAlreadyListening
  92. }
  93. }
  94. this.listeningPort = port
  95. tcpListener, err := hub.ListenTCP(port, this.HandleConnection)
  96. if err != nil {
  97. log.Error("Unable to listen tcp port ", port, ": ", err)
  98. return err
  99. }
  100. this.accepting = true
  101. this.Lock()
  102. this.listener = tcpListener
  103. this.Unlock()
  104. return nil
  105. }
  106. func (this *VMessInboundHandler) HandleConnection(connection *hub.TCPConn) {
  107. defer connection.Close()
  108. connReader := v2net.NewTimeOutReader(16, connection)
  109. reader := v2io.NewBufferedReader(connReader)
  110. session := raw.NewServerSession(this.clients)
  111. request, err := session.DecodeRequestHeader(reader)
  112. if err != nil {
  113. log.Access(connection.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
  114. log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
  115. return
  116. }
  117. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, serial.StringLiteral(""))
  118. log.Debug("VMessIn: Received request for ", request.Destination())
  119. ray := this.packetDispatcher.DispatchToOutbound(v2net.NewPacket(request.Destination(), nil, true))
  120. input := ray.InboundInput()
  121. output := ray.InboundOutput()
  122. var readFinish, writeFinish sync.Mutex
  123. readFinish.Lock()
  124. writeFinish.Lock()
  125. userSettings := proto.GetUserSettings(request.User.Level)
  126. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  127. reader.SetCached(false)
  128. go func() {
  129. defer close(input)
  130. defer readFinish.Unlock()
  131. bodyReader := session.DecodeRequestBody(reader)
  132. var requestReader v2io.Reader
  133. if request.Option.IsChunkStream() {
  134. requestReader = vmessio.NewAuthChunkReader(bodyReader)
  135. } else {
  136. requestReader = v2io.NewAdaptiveReader(bodyReader)
  137. }
  138. v2io.ReaderToChan(input, requestReader)
  139. }()
  140. writer := v2io.NewBufferedWriter(connection)
  141. response := &proto.ResponseHeader{
  142. Command: this.generateCommand(request),
  143. }
  144. session.EncodeResponseHeader(response, writer)
  145. bodyWriter := session.EncodeResponseBody(writer)
  146. // Optimize for small response packet
  147. if data, open := <-output; open {
  148. if request.Option.IsChunkStream() {
  149. vmessio.Authenticate(data)
  150. }
  151. bodyWriter.Write(data.Value)
  152. data.Release()
  153. writer.SetCached(false)
  154. go func(finish *sync.Mutex) {
  155. var writer v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
  156. if request.Option.IsChunkStream() {
  157. writer = vmessio.NewAuthChunkWriter(writer)
  158. }
  159. v2io.ChanToWriter(writer, output)
  160. finish.Unlock()
  161. }(&writeFinish)
  162. writeFinish.Lock()
  163. }
  164. connection.CloseWrite()
  165. readFinish.Lock()
  166. }
  167. func init() {
  168. internal.MustRegisterInboundHandlerCreator("vmess",
  169. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  170. if !space.HasApp(dispatcher.APP_ID) {
  171. return nil, internal.ErrorBadConfiguration
  172. }
  173. config := rawConfig.(*Config)
  174. allowedClients := proto.NewTimedUserValidator(protocol.IDHash)
  175. for _, user := range config.AllowedUsers {
  176. allowedClients.Add(user)
  177. }
  178. handler := &VMessInboundHandler{
  179. packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  180. clients: allowedClients,
  181. features: config.Features,
  182. usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
  183. }
  184. if space.HasApp(proxyman.APP_ID_INBOUND_MANAGER) {
  185. handler.inboundHandlerManager = space.GetApp(proxyman.APP_ID_INBOUND_MANAGER).(proxyman.InboundHandlerManager)
  186. }
  187. return handler, nil
  188. })
  189. }