inbound.go 7.0 KB

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