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/internet"
  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. account := &protocol.VMessAccount{
  50. ID: id,
  51. AlterIDs: alterIDs,
  52. }
  53. user = protocol.NewUser(account, this.defaultLevel, email)
  54. this.cache[email] = user
  55. }
  56. this.Unlock()
  57. }
  58. return user, found
  59. }
  60. // Inbound connection handler that handles messages in VMess format.
  61. type VMessInboundHandler struct {
  62. sync.Mutex
  63. packetDispatcher dispatcher.PacketDispatcher
  64. inboundHandlerManager proxyman.InboundHandlerManager
  65. clients protocol.UserValidator
  66. usersByEmail *userByEmail
  67. accepting bool
  68. listener *internet.TCPHub
  69. detours *DetourConfig
  70. meta *proxy.InboundHandlerMeta
  71. }
  72. func (this *VMessInboundHandler) Port() v2net.Port {
  73. return this.meta.Port
  74. }
  75. func (this *VMessInboundHandler) Close() {
  76. this.accepting = false
  77. if this.listener != nil {
  78. this.Lock()
  79. this.listener.Close()
  80. this.listener = nil
  81. this.clients.Release()
  82. this.clients = 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) Start() error {
  94. if this.accepting {
  95. return nil
  96. }
  97. tcpListener, err := internet.ListenTCP(this.meta.Address, this.meta.Port, this.HandleConnection, this.meta.StreamSettings)
  98. if err != nil {
  99. log.Error("Unable to listen tcp ", this.meta.Address, ":", this.meta.Port, ": ", err)
  100. return err
  101. }
  102. this.accepting = true
  103. this.Lock()
  104. this.listener = tcpListener
  105. this.Unlock()
  106. return nil
  107. }
  108. func (this *VMessInboundHandler) HandleConnection(connection internet.Connection) {
  109. defer connection.Close()
  110. connReader := v2net.NewTimeOutReader(8, connection)
  111. defer connReader.Release()
  112. reader := v2io.NewBufferedReader(connReader)
  113. defer reader.Release()
  114. session := raw.NewServerSession(this.clients)
  115. defer session.Release()
  116. request, err := session.DecodeRequestHeader(reader)
  117. if err != nil {
  118. if err != io.EOF {
  119. log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
  120. log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
  121. }
  122. connection.SetReusable(false)
  123. return
  124. }
  125. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
  126. log.Info("VMessIn: Received request for ", request.Destination())
  127. connection.SetReusable(request.Option.Has(protocol.RequestOptionConnectionReuse))
  128. ray := this.packetDispatcher.DispatchToOutbound(request.Destination())
  129. input := ray.InboundInput()
  130. output := ray.InboundOutput()
  131. defer input.Close()
  132. defer output.Release()
  133. var readFinish sync.Mutex
  134. readFinish.Lock()
  135. userSettings := protocol.GetUserSettings(request.User.Level)
  136. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  137. reader.SetCached(false)
  138. go func() {
  139. bodyReader := session.DecodeRequestBody(reader)
  140. var requestReader v2io.Reader
  141. if request.Option.Has(protocol.RequestOptionChunkStream) {
  142. requestReader = vmessio.NewAuthChunkReader(bodyReader)
  143. } else {
  144. requestReader = v2io.NewAdaptiveReader(bodyReader)
  145. }
  146. err := v2io.Pipe(requestReader, input)
  147. if err != io.EOF {
  148. connection.SetReusable(false)
  149. }
  150. requestReader.Release()
  151. input.Close()
  152. readFinish.Unlock()
  153. }()
  154. writer := v2io.NewBufferedWriter(connection)
  155. defer writer.Release()
  156. response := &protocol.ResponseHeader{
  157. Command: this.generateCommand(request),
  158. }
  159. if connection.Reusable() {
  160. response.Option.Set(protocol.ResponseOptionConnectionReuse)
  161. }
  162. session.EncodeResponseHeader(response, writer)
  163. bodyWriter := session.EncodeResponseBody(writer)
  164. var v2writer v2io.Writer = v2io.NewAdaptiveWriter(bodyWriter)
  165. if request.Option.Has(protocol.RequestOptionChunkStream) {
  166. v2writer = vmessio.NewAuthChunkWriter(v2writer)
  167. }
  168. // Optimize for small response packet
  169. if data, err := output.Read(); err == nil {
  170. if err := v2writer.Write(data); err != nil {
  171. connection.SetReusable(false)
  172. }
  173. writer.SetCached(false)
  174. err = v2io.Pipe(output, v2writer)
  175. if err != io.EOF {
  176. connection.SetReusable(false)
  177. }
  178. }
  179. output.Release()
  180. if request.Option.Has(protocol.RequestOptionChunkStream) {
  181. if err := v2writer.Write(alloc.NewSmallBuffer().Clear()); err != nil {
  182. connection.SetReusable(false)
  183. }
  184. }
  185. v2writer.Release()
  186. readFinish.Lock()
  187. }
  188. type Factory struct{}
  189. func (this *Factory) StreamCapability() internet.StreamConnectionType {
  190. return internet.StreamConnectionTypeRawTCP | internet.StreamConnectionTypeTCP | internet.StreamConnectionTypeKCP
  191. }
  192. func (this *Factory) Create(space app.Space, rawConfig interface{}, meta *proxy.InboundHandlerMeta) (proxy.InboundHandler, error) {
  193. if !space.HasApp(dispatcher.APP_ID) {
  194. return nil, internal.ErrorBadConfiguration
  195. }
  196. config := rawConfig.(*Config)
  197. allowedClients := protocol.NewTimedUserValidator(protocol.DefaultIDHash)
  198. for _, user := range config.AllowedUsers {
  199. allowedClients.Add(user)
  200. }
  201. handler := &VMessInboundHandler{
  202. packetDispatcher: space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher),
  203. clients: allowedClients,
  204. detours: config.DetourConfig,
  205. usersByEmail: NewUserByEmail(config.AllowedUsers, config.Defaults),
  206. meta: meta,
  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. func init() {
  214. internal.MustRegisterInboundHandlerCreator("vmess", new(Factory))
  215. }