inbound.go 7.0 KB

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