inbound.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package inbound
  2. import (
  3. "crypto/md5"
  4. "io"
  5. "sync"
  6. "github.com/v2ray/v2ray-core/app"
  7. "github.com/v2ray/v2ray-core/app/dispatcher"
  8. "github.com/v2ray/v2ray-core/app/proxyman"
  9. "github.com/v2ray/v2ray-core/common/alloc"
  10. v2crypto "github.com/v2ray/v2ray-core/common/crypto"
  11. v2io "github.com/v2ray/v2ray-core/common/io"
  12. "github.com/v2ray/v2ray-core/common/log"
  13. v2net "github.com/v2ray/v2ray-core/common/net"
  14. proto "github.com/v2ray/v2ray-core/common/protocol"
  15. "github.com/v2ray/v2ray-core/common/serial"
  16. "github.com/v2ray/v2ray-core/common/uuid"
  17. "github.com/v2ray/v2ray-core/proxy"
  18. "github.com/v2ray/v2ray-core/proxy/internal"
  19. vmessio "github.com/v2ray/v2ray-core/proxy/vmess/io"
  20. "github.com/v2ray/v2ray-core/proxy/vmess/protocol"
  21. "github.com/v2ray/v2ray-core/transport/hub"
  22. )
  23. type userByEmail struct {
  24. sync.RWMutex
  25. cache map[string]*proto.User
  26. defaultLevel proto.UserLevel
  27. defaultAlterIDs uint16
  28. }
  29. func NewUserByEmail(users []*proto.User, config *DefaultConfig) *userByEmail {
  30. cache := make(map[string]*proto.User)
  31. for _, user := range users {
  32. cache[user.Email] = user
  33. }
  34. return &userByEmail{
  35. cache: cache,
  36. defaultLevel: config.Level,
  37. defaultAlterIDs: config.AlterIDs,
  38. }
  39. }
  40. func (this *userByEmail) Get(email string) (*proto.User, bool) {
  41. var user *proto.User
  42. var found bool
  43. this.RLock()
  44. user, found = this.cache[email]
  45. this.RUnlock()
  46. if !found {
  47. this.Lock()
  48. user, found = this.cache[email]
  49. if !found {
  50. id := proto.NewID(uuid.New())
  51. user = proto.NewUser(id, this.defaultLevel, this.defaultAlterIDs, email)
  52. this.cache[email] = user
  53. }
  54. this.Unlock()
  55. }
  56. return user, found
  57. }
  58. // Inbound connection handler that handles messages in VMess format.
  59. type VMessInboundHandler struct {
  60. sync.Mutex
  61. packetDispatcher dispatcher.PacketDispatcher
  62. inboundHandlerManager proxyman.InboundHandlerManager
  63. clients proto.UserValidator
  64. usersByEmail *userByEmail
  65. accepting bool
  66. listener *hub.TCPHub
  67. features *FeaturesConfig
  68. listeningPort v2net.Port
  69. }
  70. func (this *VMessInboundHandler) Port() v2net.Port {
  71. return this.listeningPort
  72. }
  73. func (this *VMessInboundHandler) Close() {
  74. this.accepting = false
  75. if this.listener != nil {
  76. this.Lock()
  77. this.listener.Close()
  78. this.listener = nil
  79. this.Unlock()
  80. }
  81. }
  82. func (this *VMessInboundHandler) GetUser(email string) *proto.User {
  83. user, existing := this.usersByEmail.Get(email)
  84. if !existing {
  85. this.clients.Add(user)
  86. }
  87. return user
  88. }
  89. func (this *VMessInboundHandler) Listen(port v2net.Port) error {
  90. if this.accepting {
  91. if this.listeningPort == port {
  92. return nil
  93. } else {
  94. return proxy.ErrorAlreadyListening
  95. }
  96. }
  97. this.listeningPort = port
  98. tcpListener, err := hub.ListenTCP(port, this.HandleConnection)
  99. if err != nil {
  100. log.Error("Unable to listen tcp port ", port, ": ", err)
  101. return err
  102. }
  103. this.accepting = true
  104. this.Lock()
  105. this.listener = tcpListener
  106. this.Unlock()
  107. return nil
  108. }
  109. func (this *VMessInboundHandler) HandleConnection(connection *hub.TCPConn) {
  110. defer connection.Close()
  111. connReader := v2net.NewTimeOutReader(16, connection)
  112. requestReader := protocol.NewVMessRequestReader(this.clients)
  113. request, err := requestReader.Read(connReader)
  114. if err != nil {
  115. log.Access(connection.RemoteAddr(), serial.StringLiteral(""), log.AccessRejected, serial.StringLiteral(err.Error()))
  116. log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
  117. return
  118. }
  119. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, serial.StringLiteral(""))
  120. log.Debug("VMessIn: Received request for ", request.Destination())
  121. ray := this.packetDispatcher.DispatchToOutbound(v2net.NewPacket(request.Destination(), nil, true))
  122. input := ray.InboundInput()
  123. output := ray.InboundOutput()
  124. var readFinish, writeFinish sync.Mutex
  125. readFinish.Lock()
  126. writeFinish.Lock()
  127. userSettings := proto.GetUserSettings(request.User.Level)
  128. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  129. go handleInput(request, connReader, input, &readFinish)
  130. responseKey := md5.Sum(request.RequestKey)
  131. responseIV := md5.Sum(request.RequestIV)
  132. aesStream := v2crypto.NewAesEncryptionStream(responseKey[:], responseIV[:])
  133. responseWriter := v2crypto.NewCryptionWriter(aesStream, connection)
  134. // Optimize for small response packet
  135. buffer := alloc.NewLargeBuffer().Clear()
  136. defer buffer.Release()
  137. buffer.AppendBytes(request.ResponseHeader, byte(0))
  138. this.generateCommand(request, buffer)
  139. if data, open := <-output; open {
  140. if request.IsChunkStream() {
  141. vmessio.Authenticate(data)
  142. }
  143. buffer.Append(data.Value)
  144. data.Release()
  145. responseWriter.Write(buffer.Value)
  146. go func(finish *sync.Mutex) {
  147. var writer v2io.Writer = v2io.NewAdaptiveWriter(responseWriter)
  148. if request.IsChunkStream() {
  149. writer = vmessio.NewAuthChunkWriter(writer)
  150. }
  151. v2io.ChanToWriter(writer, output)
  152. finish.Unlock()
  153. }(&writeFinish)
  154. writeFinish.Lock()
  155. }
  156. connection.CloseWrite()
  157. readFinish.Lock()
  158. }
  159. func handleInput(request *protocol.VMessRequest, reader io.Reader, input chan<- *alloc.Buffer, finish *sync.Mutex) {
  160. defer close(input)
  161. defer finish.Unlock()
  162. aesStream := v2crypto.NewAesDecryptionStream(request.RequestKey, request.RequestIV)
  163. descriptionReader := v2crypto.NewCryptionReader(aesStream, reader)
  164. var requestReader v2io.Reader
  165. if request.IsChunkStream() {
  166. requestReader = vmessio.NewAuthChunkReader(descriptionReader)
  167. } else {
  168. requestReader = v2io.NewAdaptiveReader(descriptionReader)
  169. }
  170. v2io.ReaderToChan(input, requestReader)
  171. }
  172. func init() {
  173. internal.MustRegisterInboundHandlerCreator("vmess",
  174. func(space app.Space, rawConfig interface{}) (proxy.InboundHandler, error) {
  175. if !space.HasApp(dispatcher.APP_ID) {
  176. return nil, internal.ErrorBadConfiguration
  177. }
  178. config := rawConfig.(*Config)
  179. allowedClients := proto.NewTimedUserValidator(protocol.IDHash)
  180. for _, user := range config.AllowedUsers {
  181. allowedClients.Add(user)
  182. }
  183. handler := &VMessInboundHandler{
  184. packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  185. clients: allowedClients,
  186. features: config.Features,
  187. usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
  188. }
  189. if space.HasApp(proxyman.APP_ID_INBOUND_MANAGER) {
  190. handler.inboundHandlerManager = space.GetApp(proxyman.APP_ID_INBOUND_MANAGER).(proxyman.InboundHandlerManager)
  191. }
  192. return handler, nil
  193. })
  194. }