inbound.go 6.0 KB

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