inbound.go 7.5 KB

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