inbound.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package inbound
  2. import (
  3. "context"
  4. "io"
  5. "sync"
  6. "runtime"
  7. "time"
  8. "v2ray.com/core/app"
  9. "v2ray.com/core/app/dispatcher"
  10. "v2ray.com/core/app/proxyman"
  11. "v2ray.com/core/common"
  12. "v2ray.com/core/common/buf"
  13. "v2ray.com/core/common/bufio"
  14. "v2ray.com/core/common/errors"
  15. "v2ray.com/core/app/log"
  16. "v2ray.com/core/common/net"
  17. "v2ray.com/core/common/protocol"
  18. "v2ray.com/core/common/serial"
  19. "v2ray.com/core/common/signal"
  20. "v2ray.com/core/common/uuid"
  21. "v2ray.com/core/proxy"
  22. "v2ray.com/core/proxy/vmess"
  23. "v2ray.com/core/proxy/vmess/encoding"
  24. "v2ray.com/core/transport/internet"
  25. "v2ray.com/core/transport/ray"
  26. )
  27. type userByEmail struct {
  28. sync.RWMutex
  29. cache map[string]*protocol.User
  30. defaultLevel uint32
  31. defaultAlterIDs uint16
  32. }
  33. func NewUserByEmail(users []*protocol.User, config *DefaultConfig) *userByEmail {
  34. cache := make(map[string]*protocol.User)
  35. for _, user := range users {
  36. cache[user.Email] = user
  37. }
  38. return &userByEmail{
  39. cache: cache,
  40. defaultLevel: config.Level,
  41. defaultAlterIDs: uint16(config.AlterId),
  42. }
  43. }
  44. func (v *userByEmail) Get(email string) (*protocol.User, bool) {
  45. var user *protocol.User
  46. var found bool
  47. v.RLock()
  48. user, found = v.cache[email]
  49. v.RUnlock()
  50. if !found {
  51. v.Lock()
  52. user, found = v.cache[email]
  53. if !found {
  54. account := &vmess.Account{
  55. Id: uuid.New().String(),
  56. AlterId: uint32(v.defaultAlterIDs),
  57. }
  58. user = &protocol.User{
  59. Level: v.defaultLevel,
  60. Email: email,
  61. Account: serial.ToTypedMessage(account),
  62. }
  63. v.cache[email] = user
  64. }
  65. v.Unlock()
  66. }
  67. return user, found
  68. }
  69. // Inbound connection handler that handles messages in VMess format.
  70. type VMessInboundHandler struct {
  71. sync.RWMutex
  72. packetDispatcher dispatcher.Interface
  73. inboundHandlerManager proxyman.InboundHandlerManager
  74. clients protocol.UserValidator
  75. usersByEmail *userByEmail
  76. detours *DetourConfig
  77. }
  78. func New(ctx context.Context, config *Config) (*VMessInboundHandler, error) {
  79. space := app.SpaceFromContext(ctx)
  80. if space == nil {
  81. return nil, errors.New("VMess|Inbound: No space in context.")
  82. }
  83. allowedClients := vmess.NewTimedUserValidator(ctx, protocol.DefaultIDHash)
  84. for _, user := range config.User {
  85. allowedClients.Add(user)
  86. }
  87. handler := &VMessInboundHandler{
  88. clients: allowedClients,
  89. detours: config.Detour,
  90. usersByEmail: NewUserByEmail(config.User, config.GetDefaultValue()),
  91. }
  92. space.OnInitialize(func() error {
  93. handler.packetDispatcher = dispatcher.FromSpace(space)
  94. if handler.packetDispatcher == nil {
  95. return errors.New("VMess|Inbound: Dispatcher is not found in space.")
  96. }
  97. handler.inboundHandlerManager = proxyman.InboundHandlerManagerFromSpace(space)
  98. if handler.inboundHandlerManager == nil {
  99. return errors.New("VMess|Inbound: InboundHandlerManager is not found is space.")
  100. }
  101. return nil
  102. })
  103. return handler, nil
  104. }
  105. func (*VMessInboundHandler) Network() net.NetworkList {
  106. return net.NetworkList{
  107. Network: []net.Network{net.Network_TCP},
  108. }
  109. }
  110. func (v *VMessInboundHandler) GetUser(email string) *protocol.User {
  111. v.RLock()
  112. defer v.RUnlock()
  113. user, existing := v.usersByEmail.Get(email)
  114. if !existing {
  115. v.clients.Add(user)
  116. }
  117. return user
  118. }
  119. func transferRequest(timer *signal.ActivityTimer, session *encoding.ServerSession, request *protocol.RequestHeader, input io.Reader, output ray.OutputStream) error {
  120. defer output.Close()
  121. bodyReader := session.DecodeRequestBody(request, input)
  122. if err := buf.PipeUntilEOF(timer, bodyReader, output); err != nil {
  123. return err
  124. }
  125. return nil
  126. }
  127. func transferResponse(timer *signal.ActivityTimer, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input ray.InputStream, output io.Writer) error {
  128. session.EncodeResponseHeader(response, output)
  129. bodyWriter := session.EncodeResponseBody(request, output)
  130. // Optimize for small response packet
  131. data, err := input.Read()
  132. if err != nil {
  133. return err
  134. }
  135. if err := bodyWriter.Write(data); err != nil {
  136. return err
  137. }
  138. data.Release()
  139. if bufferedWriter, ok := output.(*bufio.BufferedWriter); ok {
  140. if err := bufferedWriter.SetBuffered(false); err != nil {
  141. return err
  142. }
  143. }
  144. if err := buf.PipeUntilEOF(timer, input, bodyWriter); err != nil {
  145. return err
  146. }
  147. if request.Option.Has(protocol.RequestOptionChunkStream) {
  148. if err := bodyWriter.Write(buf.NewLocal(8)); err != nil {
  149. return err
  150. }
  151. }
  152. return nil
  153. }
  154. func (v *VMessInboundHandler) Process(ctx context.Context, network net.Network, connection internet.Connection) error {
  155. connection.SetReadDeadline(time.Now().Add(time.Second * 8))
  156. reader := bufio.NewReader(connection)
  157. session := encoding.NewServerSession(v.clients)
  158. request, err := session.DecodeRequestHeader(reader)
  159. if err != nil {
  160. if errors.Cause(err) != io.EOF {
  161. log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
  162. log.Info("VMess|Inbound: Invalid request from ", connection.RemoteAddr(), ": ", err)
  163. }
  164. connection.SetReusable(false)
  165. return err
  166. }
  167. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
  168. log.Info("VMess|Inbound: Received request for ", request.Destination())
  169. connection.SetReadDeadline(time.Time{})
  170. connection.SetReusable(request.Option.Has(protocol.RequestOptionConnectionReuse))
  171. userSettings := request.User.GetSettings()
  172. ctx = proxy.ContextWithDestination(ctx, request.Destination())
  173. ctx = protocol.ContextWithUser(ctx, request.User)
  174. ctx, cancel := context.WithCancel(ctx)
  175. timer := signal.CancelAfterInactivity(ctx, cancel, userSettings.PayloadTimeout)
  176. ray := v.packetDispatcher.DispatchToOutbound(ctx)
  177. input := ray.InboundInput()
  178. output := ray.InboundOutput()
  179. reader.SetBuffered(false)
  180. requestDone := signal.ExecuteAsync(func() error {
  181. return transferRequest(timer, session, request, reader, input)
  182. })
  183. writer := bufio.NewWriter(connection)
  184. response := &protocol.ResponseHeader{
  185. Command: v.generateCommand(ctx, request),
  186. }
  187. if connection.Reusable() {
  188. response.Option.Set(protocol.ResponseOptionConnectionReuse)
  189. }
  190. responseDone := signal.ExecuteAsync(func() error {
  191. return transferResponse(timer, session, request, response, output, writer)
  192. })
  193. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  194. log.Info("VMess|Inbound: Connection ending with ", err)
  195. connection.SetReusable(false)
  196. input.CloseError()
  197. output.CloseError()
  198. return err
  199. }
  200. if err := writer.Flush(); err != nil {
  201. log.Info("VMess|Inbound: Failed to flush remain data: ", err)
  202. connection.SetReusable(false)
  203. return err
  204. }
  205. runtime.KeepAlive(timer)
  206. return nil
  207. }
  208. func (v *VMessInboundHandler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand {
  209. if v.detours != nil {
  210. tag := v.detours.To
  211. if v.inboundHandlerManager != nil {
  212. handler, err := v.inboundHandlerManager.GetHandler(ctx, tag)
  213. if err != nil {
  214. log.Warning("VMess|Inbound: Failed to get detour handler: ", tag, err)
  215. return nil
  216. }
  217. proxyHandler, port, availableMin := handler.GetRandomInboundProxy()
  218. inboundHandler, ok := proxyHandler.(*VMessInboundHandler)
  219. if ok {
  220. if availableMin > 255 {
  221. availableMin = 255
  222. }
  223. log.Info("VMessIn: Pick detour handler for port ", port, " for ", availableMin, " minutes.")
  224. user := inboundHandler.GetUser(request.User.Email)
  225. if user == nil {
  226. return nil
  227. }
  228. account, _ := user.GetTypedAccount()
  229. return &protocol.CommandSwitchAccount{
  230. Port: port,
  231. ID: account.(*vmess.InternalAccount).ID.UUID(),
  232. AlterIds: uint16(len(account.(*vmess.InternalAccount).AlterIDs)),
  233. Level: user.Level,
  234. ValidMin: byte(availableMin),
  235. }
  236. }
  237. }
  238. }
  239. return nil
  240. }
  241. func init() {
  242. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  243. return New(ctx, config.(*Config))
  244. }))
  245. }