inbound.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package inbound
  2. import (
  3. "context"
  4. "io"
  5. "runtime"
  6. "sync"
  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. sessionHistory *encoding.SessionHistory
  75. }
  76. func New(ctx context.Context, config *Config) (*VMessInboundHandler, error) {
  77. space := app.SpaceFromContext(ctx)
  78. if space == nil {
  79. return nil, errors.New("VMess|Inbound: No space in context.")
  80. }
  81. allowedClients := vmess.NewTimedUserValidator(ctx, protocol.DefaultIDHash)
  82. for _, user := range config.User {
  83. allowedClients.Add(user)
  84. }
  85. handler := &VMessInboundHandler{
  86. clients: allowedClients,
  87. detours: config.Detour,
  88. usersByEmail: NewUserByEmail(config.User, config.GetDefaultValue()),
  89. sessionHistory: encoding.NewSessionHistory(ctx),
  90. }
  91. space.OnInitialize(func() error {
  92. handler.inboundHandlerManager = proxyman.InboundHandlerManagerFromSpace(space)
  93. if handler.inboundHandlerManager == nil {
  94. return errors.New("VMess|Inbound: InboundHandlerManager is not found is space.")
  95. }
  96. return nil
  97. })
  98. return handler, nil
  99. }
  100. func (*VMessInboundHandler) Network() net.NetworkList {
  101. return net.NetworkList{
  102. Network: []net.Network{net.Network_TCP},
  103. }
  104. }
  105. func (v *VMessInboundHandler) GetUser(email string) *protocol.User {
  106. user, existing := v.usersByEmail.Get(email)
  107. if !existing {
  108. v.clients.Add(user)
  109. }
  110. return user
  111. }
  112. func transferRequest(timer *signal.ActivityTimer, session *encoding.ServerSession, request *protocol.RequestHeader, input io.Reader, output ray.OutputStream) error {
  113. defer output.Close()
  114. bodyReader := session.DecodeRequestBody(request, input)
  115. if err := buf.PipeUntilEOF(timer, bodyReader, output); err != nil {
  116. return err
  117. }
  118. return nil
  119. }
  120. func transferResponse(timer *signal.ActivityTimer, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input ray.InputStream, output io.Writer) error {
  121. session.EncodeResponseHeader(response, output)
  122. bodyWriter := session.EncodeResponseBody(request, output)
  123. // Optimize for small response packet
  124. data, err := input.Read()
  125. if err != nil {
  126. return err
  127. }
  128. if err := bodyWriter.Write(data); err != nil {
  129. return err
  130. }
  131. data.Release()
  132. if bufferedWriter, ok := output.(*bufio.BufferedWriter); ok {
  133. if err := bufferedWriter.SetBuffered(false); err != nil {
  134. return err
  135. }
  136. }
  137. if err := buf.PipeUntilEOF(timer, input, bodyWriter); err != nil {
  138. return err
  139. }
  140. if request.Option.Has(protocol.RequestOptionChunkStream) {
  141. if err := bodyWriter.Write(buf.NewLocal(8)); err != nil {
  142. return err
  143. }
  144. }
  145. return nil
  146. }
  147. func (v *VMessInboundHandler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher dispatcher.Interface) error {
  148. connection.SetReadDeadline(time.Now().Add(time.Second * 8))
  149. reader := bufio.NewReader(connection)
  150. session := encoding.NewServerSession(v.clients, v.sessionHistory)
  151. request, err := session.DecodeRequestHeader(reader)
  152. if err != nil {
  153. if errors.Cause(err) != io.EOF {
  154. log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
  155. log.Info("VMess|Inbound: Invalid request from ", connection.RemoteAddr(), ": ", err)
  156. }
  157. connection.SetReusable(false)
  158. return err
  159. }
  160. log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
  161. log.Info("VMess|Inbound: Received request for ", request.Destination())
  162. connection.SetReadDeadline(time.Time{})
  163. connection.SetReusable(request.Option.Has(protocol.RequestOptionConnectionReuse))
  164. userSettings := request.User.GetSettings()
  165. ctx = protocol.ContextWithUser(ctx, request.User)
  166. ctx, cancel := context.WithCancel(ctx)
  167. timer := signal.CancelAfterInactivity(ctx, cancel, userSettings.PayloadTimeout)
  168. ray, err := dispatcher.Dispatch(ctx, request.Destination())
  169. if err != nil {
  170. return err
  171. }
  172. input := ray.InboundInput()
  173. output := ray.InboundOutput()
  174. reader.SetBuffered(false)
  175. requestDone := signal.ExecuteAsync(func() error {
  176. return transferRequest(timer, session, request, reader, input)
  177. })
  178. writer := bufio.NewWriter(connection)
  179. response := &protocol.ResponseHeader{
  180. Command: v.generateCommand(ctx, request),
  181. }
  182. if connection.Reusable() {
  183. response.Option.Set(protocol.ResponseOptionConnectionReuse)
  184. }
  185. responseDone := signal.ExecuteAsync(func() error {
  186. return transferResponse(timer, session, request, response, output, writer)
  187. })
  188. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  189. connection.SetReusable(false)
  190. input.CloseError()
  191. output.CloseError()
  192. return errors.Base(err).Message("VMess|Inbound: Error during processing.")
  193. }
  194. if err := writer.Flush(); err != nil {
  195. connection.SetReusable(false)
  196. return errors.Base(err).Message("VMess|Inbound: Error during flushing remaining data.")
  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 && inboundHandler != nil {
  213. if availableMin > 255 {
  214. availableMin = 255
  215. }
  216. log.Info("VMess|Inbound: 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. }