inbound.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. meta *proxy.InboundHandlerMeta
  72. }
  73. func (this *VMessInboundHandler) Port() v2net.Port {
  74. return this.meta.Port
  75. }
  76. func (this *VMessInboundHandler) Close() {
  77. this.accepting = false
  78. if this.listener != nil {
  79. this.Lock()
  80. this.listener.Close()
  81. this.listener = nil
  82. this.clients.Release()
  83. this.clients = nil
  84. this.Unlock()
  85. }
  86. }
  87. func (this *VMessInboundHandler) GetUser(email string) *protocol.User {
  88. user, existing := this.usersByEmail.Get(email)
  89. if !existing {
  90. this.clients.Add(user)
  91. }
  92. return user
  93. }
  94. func (this *VMessInboundHandler) Start() error {
  95. if this.accepting {
  96. return nil
  97. }
  98. tcpListener, err := hub.ListenTCP6(this.meta.Address, this.meta.Port, this.HandleConnection, this.meta, nil)
  99. if err != nil {
  100. log.Error("Unable to listen tcp ", this.meta.Address, ":", this.meta.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.Connection) {
  110. defer connection.Close()
  111. connReader := v2net.NewTimeOutReader(8, connection)
  112. defer connReader.Release()
  113. reader := v2io.NewBufferedReader(connReader)
  114. defer reader.Release()
  115. session := raw.NewServerSession(this.clients)
  116. defer session.Release()
  117. request, err := session.DecodeRequestHeader(reader)
  118. if err != nil {
  119. if err != io.EOF {
  120. log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
  121. log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
  122. }
  123. connection.SetReusable(false)
  124. return
  125. }
  126. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
  127. log.Debug("VMessIn: Received request for ", request.Destination())
  128. if request.Option.Has(protocol.RequestOptionConnectionReuse) {
  129. connection.SetReusable(true)
  130. }
  131. ray := this.packetDispatcher.DispatchToOutbound(request.Destination())
  132. input := ray.InboundInput()
  133. output := ray.InboundOutput()
  134. defer input.Close()
  135. defer output.Release()
  136. var readFinish sync.Mutex
  137. readFinish.Lock()
  138. userSettings := protocol.GetUserSettings(request.User.Level)
  139. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  140. reader.SetCached(false)
  141. go func() {
  142. bodyReader := session.DecodeRequestBody(reader)
  143. var requestReader v2io.Reader
  144. if request.Option.Has(protocol.RequestOptionChunkStream) {
  145. requestReader = vmessio.NewAuthChunkReader(bodyReader)
  146. } else {
  147. requestReader = v2io.NewAdaptiveReader(bodyReader)
  148. }
  149. err := v2io.Pipe(requestReader, input)
  150. if err != io.EOF {
  151. connection.SetReusable(false)
  152. }
  153. requestReader.Release()
  154. input.Close()
  155. readFinish.Unlock()
  156. }()
  157. writer := v2io.NewBufferedWriter(connection)
  158. defer writer.Release()
  159. response := &protocol.ResponseHeader{
  160. Command: this.generateCommand(request),
  161. }
  162. if request.Option.Has(protocol.RequestOptionConnectionReuse) && transport.IsConnectionReusable() {
  163. response.Option.Set(protocol.ResponseOptionConnectionReuse)
  164. }
  165. session.EncodeResponseHeader(response, writer)
  166. bodyWriter := session.EncodeResponseBody(writer)
  167. var v2writer v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
  168. if request.Option.Has(protocol.RequestOptionChunkStream) {
  169. v2writer = vmessio.NewAuthChunkWriter(v2writer)
  170. }
  171. // Optimize for small response packet
  172. if data, err := output.Read(); err == nil {
  173. if err := v2writer.Write(data); err != nil {
  174. connection.SetReusable(false)
  175. }
  176. writer.SetCached(false)
  177. err = v2io.Pipe(output, v2writer)
  178. if err != io.EOF {
  179. connection.SetReusable(false)
  180. }
  181. }
  182. output.Release()
  183. if request.Option.Has(protocol.RequestOptionChunkStream) {
  184. if err := v2writer.Write(alloc.NewSmallBuffer().Clear()); err != nil {
  185. connection.SetReusable(false)
  186. }
  187. }
  188. v2writer.Release()
  189. readFinish.Lock()
  190. }
  191. func (this *VMessInboundHandler) setProxyCap() {
  192. this.meta.KcpSupported = true
  193. }
  194. func init() {
  195. internal.MustRegisterInboundHandlerCreator("vmess",
  196. func(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  197. if !space.HasApp(dispatcher.APP_ID) {
  198. return nil, internal.ErrorBadConfiguration
  199. }
  200. config := rawConfig.(*Config)
  201. allowedClients := protocol.NewTimedUserValidator(protocol.DefaultIDHash)
  202. for _, user := range config.AllowedUsers {
  203. allowedClients.Add(user)
  204. }
  205. handler := &VMessInboundHandler{
  206. packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  207. clients: allowedClients,
  208. detours: config.DetourConfig,
  209. usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
  210. meta: meta,
  211. }
  212. if space.HasApp(proxyman.APP_ID_INBOUND_MANAGER) {
  213. handler.inboundHandlerManager = space.GetApp(proxyman.APP_ID_INBOUND_MANAGER).(proxyman.InboundHandlerManager)
  214. }
  215. handler.setProxyCap()
  216. return handler, nil
  217. })
  218. }