inbound.go 7.0 KB

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