inbound.go 6.0 KB

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