inbound.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. user = protocol.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 protocol.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) *protocol.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, nil)
  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.Connection) {
  107. defer connection.Close()
  108. connReader := v2net.NewTimeOutReader(16, connection)
  109. defer connReader.Release()
  110. reader := v2io.NewBufferedReader(connReader)
  111. defer reader.Release()
  112. session := raw.NewServerSession(this.clients)
  113. defer session.Release()
  114. request, err := session.DecodeRequestHeader(reader)
  115. if err != nil {
  116. log.Access(connection.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
  117. log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
  118. return
  119. }
  120. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, serial.StringLiteral(""))
  121. log.Debug("VMessIn: Received request for ", request.Destination())
  122. ray := this.packetDispatcher.DispatchToOutbound(request.Destination())
  123. input := ray.InboundInput()
  124. output := ray.InboundOutput()
  125. defer input.Close()
  126. defer output.Release()
  127. var readFinish, writeFinish sync.Mutex
  128. readFinish.Lock()
  129. writeFinish.Lock()
  130. userSettings := protocol.GetUserSettings(request.User.Level)
  131. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  132. reader.SetCached(false)
  133. go func() {
  134. defer input.Close()
  135. defer readFinish.Unlock()
  136. bodyReader := session.DecodeRequestBody(reader)
  137. var requestReader v2io.Reader
  138. if request.Option.IsChunkStream() {
  139. requestReader = vmessio.NewAuthChunkReader(bodyReader)
  140. } else {
  141. requestReader = v2io.NewAdaptiveReader(bodyReader)
  142. }
  143. v2io.Pipe(requestReader, input)
  144. requestReader.Release()
  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. if request.Option.IsChunkStream() {
  156. vmessio.Authenticate(data)
  157. }
  158. bodyWriter.Write(data.Value)
  159. data.Release()
  160. writer.SetCached(false)
  161. go func(finish *sync.Mutex) {
  162. var writer v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
  163. if request.Option.IsChunkStream() {
  164. writer = vmessio.NewAuthChunkWriter(writer)
  165. }
  166. v2io.Pipe(output, writer)
  167. if request.Option.IsChunkStream() {
  168. writer.Write(alloc.NewSmallBuffer().Clear())
  169. }
  170. writer.Release()
  171. finish.Unlock()
  172. }(&writeFinish)
  173. writeFinish.Lock()
  174. }
  175. readFinish.Lock()
  176. }
  177. func init() {
  178. internal.MustRegisterInboundHandlerCreator("vmess",
  179. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  180. if !space.HasApp(dispatcher.APP_ID) {
  181. return nil, internal.ErrorBadConfiguration
  182. }
  183. config := rawConfig.(*Config)
  184. allowedClients := protocol.NewTimedUserValidator(protocol.DefaultIDHash)
  185. for _, user := range config.AllowedUsers {
  186. allowedClients.Add(user)
  187. }
  188. handler := &VMessInboundHandler{
  189. packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  190. clients: allowedClients,
  191. features: config.Features,
  192. usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
  193. }
  194. if space.HasApp(proxyman.APP_ID_INBOUND_MANAGER) {
  195. handler.inboundHandlerManager = space.GetApp(proxyman.APP_ID_INBOUND_MANAGER).(proxyman.InboundHandlerManager)
  196. }
  197. return handler, nil
  198. })
  199. }