inbound.go 6.0 KB

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