inbound.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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, writeFinish sync.Mutex
  129. readFinish.Lock()
  130. writeFinish.Lock()
  131. userSettings := protocol.GetUserSettings(request.User.Level)
  132. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  133. reader.SetCached(false)
  134. go func() {
  135. bodyReader := session.DecodeRequestBody(reader)
  136. var requestReader v2io.Reader
  137. if request.Option.IsChunkStream() {
  138. requestReader = vmessio.NewAuthChunkReader(bodyReader)
  139. } else {
  140. requestReader = v2io.NewAdaptiveReader(bodyReader)
  141. }
  142. v2io.Pipe(requestReader, input)
  143. requestReader.Release()
  144. input.Close()
  145. readFinish.Unlock()
  146. }()
  147. writer := v2io.NewBufferedWriter(connection)
  148. defer writer.Release()
  149. response := &protocol.ResponseHeader{
  150. Command: this.generateCommand(request),
  151. }
  152. session.EncodeResponseHeader(response, writer)
  153. bodyWriter := session.EncodeResponseBody(writer)
  154. // Optimize for small response packet
  155. if data, err := output.Read(); err == nil {
  156. if request.Option.IsChunkStream() {
  157. vmessio.Authenticate(data)
  158. }
  159. bodyWriter.Write(data.Value)
  160. data.Release()
  161. writer.SetCached(false)
  162. go func(finish *sync.Mutex) {
  163. var writer v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
  164. if request.Option.IsChunkStream() {
  165. writer = vmessio.NewAuthChunkWriter(writer)
  166. }
  167. v2io.Pipe(output, writer)
  168. output.Release()
  169. if request.Option.IsChunkStream() {
  170. writer.Write(alloc.NewSmallBuffer().Clear())
  171. }
  172. writer.Release()
  173. finish.Unlock()
  174. }(&writeFinish)
  175. writeFinish.Lock()
  176. }
  177. readFinish.Lock()
  178. }
  179. func init() {
  180. internal.MustRegisterInboundHandlerCreator("vmess",
  181. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  182. if !space.HasApp(dispatcher.APP_ID) {
  183. return nil, internal.ErrorBadConfiguration
  184. }
  185. config := rawConfig.(*Config)
  186. allowedClients := protocol.NewTimedUserValidator(protocol.DefaultIDHash)
  187. for _, user := range config.AllowedUsers {
  188. allowedClients.Add(user)
  189. }
  190. handler := &VMessInboundHandler{
  191. packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  192. clients: allowedClients,
  193. features: config.Features,
  194. usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
  195. }
  196. if space.HasApp(proxyman.APP_ID_INBOUND_MANAGER) {
  197. handler.inboundHandlerManager = space.GetApp(proxyman.APP_ID_INBOUND_MANAGER).(proxyman.InboundHandlerManager)
  198. }
  199. return handler, nil
  200. })
  201. }