inbound.go 7.2 KB

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