inbound.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. reader := v2io.NewBufferedReader(connReader)
  109. session := raw.NewServerSession(this.clients)
  110. request, err := session.DecodeRequestHeader(reader)
  111. if err != nil {
  112. log.Access(connection.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
  113. log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
  114. return
  115. }
  116. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, serial.StringLiteral(""))
  117. log.Debug("VMessIn: Received request for ", request.Destination())
  118. ray := this.packetDispatcher.DispatchToOutbound(v2net.NewPacket(request.Destination(), nil, true))
  119. input := ray.InboundInput()
  120. output := ray.InboundOutput()
  121. var readFinish, writeFinish sync.Mutex
  122. readFinish.Lock()
  123. writeFinish.Lock()
  124. userSettings := proto.GetUserSettings(request.User.Level)
  125. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  126. reader.SetCached(false)
  127. go func() {
  128. defer close(input)
  129. defer readFinish.Unlock()
  130. bodyReader := session.DecodeRequestBody(reader)
  131. var requestReader v2io.Reader
  132. if request.Option.IsChunkStream() {
  133. requestReader = vmessio.NewAuthChunkReader(bodyReader)
  134. } else {
  135. requestReader = v2io.NewAdaptiveReader(bodyReader)
  136. }
  137. v2io.ReaderToChan(input, requestReader)
  138. }()
  139. writer := v2io.NewBufferedWriter(connection)
  140. response := &proto.ResponseHeader{
  141. Command: this.generateCommand(request),
  142. }
  143. session.EncodeResponseHeader(response, writer)
  144. bodyWriter := session.EncodeResponseBody(writer)
  145. // Optimize for small response packet
  146. if data, open := <-output; open {
  147. if request.Option.IsChunkStream() {
  148. vmessio.Authenticate(data)
  149. }
  150. bodyWriter.Write(data.Value)
  151. data.Release()
  152. writer.SetCached(false)
  153. go func(finish *sync.Mutex) {
  154. var writer v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
  155. if request.Option.IsChunkStream() {
  156. writer = vmessio.NewAuthChunkWriter(writer)
  157. }
  158. v2io.ChanToWriter(writer, output)
  159. finish.Unlock()
  160. }(&writeFinish)
  161. writeFinish.Lock()
  162. }
  163. connection.CloseWrite()
  164. readFinish.Lock()
  165. }
  166. func init() {
  167. internal.MustRegisterInboundHandlerCreator("vmess",
  168. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  169. if !space.HasApp(dispatcher.APP_ID) {
  170. return nil, internal.ErrorBadConfiguration
  171. }
  172. config := rawConfig.(*Config)
  173. allowedClients := proto.NewTimedUserValidator(proto.DefaultIDHash)
  174. for _, user := range config.AllowedUsers {
  175. allowedClients.Add(user)
  176. }
  177. handler := &VMessInboundHandler{
  178. packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  179. clients: allowedClients,
  180. features: config.Features,
  181. usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
  182. }
  183. if space.HasApp(proxyman.APP_ID_INBOUND_MANAGER) {
  184. handler.inboundHandlerManager = space.GetApp(proxyman.APP_ID_INBOUND_MANAGER).(proxyman.InboundHandlerManager)
  185. }
  186. return handler, nil
  187. })
  188. }