inbound.go 7.3 KB

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