inbound.go 6.7 KB

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