inbound.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package inbound
  2. //go:generate errorgen
  3. import (
  4. "context"
  5. "io"
  6. "strings"
  7. "sync"
  8. "time"
  9. "v2ray.com/core"
  10. "v2ray.com/core/common"
  11. "v2ray.com/core/common/buf"
  12. "v2ray.com/core/common/errors"
  13. "v2ray.com/core/common/log"
  14. "v2ray.com/core/common/net"
  15. "v2ray.com/core/common/protocol"
  16. "v2ray.com/core/common/session"
  17. "v2ray.com/core/common/signal"
  18. "v2ray.com/core/common/task"
  19. "v2ray.com/core/common/uuid"
  20. feature_inbound "v2ray.com/core/features/inbound"
  21. "v2ray.com/core/features/policy"
  22. "v2ray.com/core/features/routing"
  23. "v2ray.com/core/proxy/vmess"
  24. "v2ray.com/core/proxy/vmess/encoding"
  25. "v2ray.com/core/transport/internet"
  26. )
  27. type userByEmail struct {
  28. sync.Mutex
  29. cache map[string]*protocol.MemoryUser
  30. defaultLevel uint32
  31. defaultAlterIDs uint16
  32. }
  33. func newUserByEmail(config *DefaultConfig) *userByEmail {
  34. return &userByEmail{
  35. cache: make(map[string]*protocol.MemoryUser),
  36. defaultLevel: config.Level,
  37. defaultAlterIDs: uint16(config.AlterId),
  38. }
  39. }
  40. func (v *userByEmail) addNoLock(u *protocol.MemoryUser) bool {
  41. email := strings.ToLower(u.Email)
  42. user, found := v.cache[email]
  43. if found {
  44. return false
  45. }
  46. v.cache[email] = user
  47. return true
  48. }
  49. func (v *userByEmail) Add(u *protocol.MemoryUser) bool {
  50. v.Lock()
  51. defer v.Unlock()
  52. return v.addNoLock(u)
  53. }
  54. func (v *userByEmail) Get(email string) (*protocol.MemoryUser, bool) {
  55. email = strings.ToLower(email)
  56. v.Lock()
  57. defer v.Unlock()
  58. user, found := v.cache[email]
  59. if !found {
  60. id := uuid.New()
  61. rawAccount := &vmess.Account{
  62. Id: id.String(),
  63. AlterId: uint32(v.defaultAlterIDs),
  64. }
  65. account, err := rawAccount.AsAccount()
  66. common.Must(err)
  67. user = &protocol.MemoryUser{
  68. Level: v.defaultLevel,
  69. Email: email,
  70. Account: account,
  71. }
  72. v.cache[email] = user
  73. }
  74. return user, found
  75. }
  76. func (v *userByEmail) Remove(email string) bool {
  77. email = strings.ToLower(email)
  78. v.Lock()
  79. defer v.Unlock()
  80. if _, found := v.cache[email]; !found {
  81. return false
  82. }
  83. delete(v.cache, email)
  84. return true
  85. }
  86. // Handler is an inbound connection handler that handles messages in VMess protocol.
  87. type Handler struct {
  88. policyManager policy.Manager
  89. inboundHandlerManager feature_inbound.Manager
  90. clients *vmess.TimedUserValidator
  91. usersByEmail *userByEmail
  92. detours *DetourConfig
  93. sessionHistory *encoding.SessionHistory
  94. secure bool
  95. }
  96. // New creates a new VMess inbound handler.
  97. func New(ctx context.Context, config *Config) (*Handler, error) {
  98. v := core.MustFromContext(ctx)
  99. handler := &Handler{
  100. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  101. inboundHandlerManager: v.GetFeature(feature_inbound.ManagerType()).(feature_inbound.Manager),
  102. clients: vmess.NewTimedUserValidator(protocol.DefaultIDHash),
  103. detours: config.Detour,
  104. usersByEmail: newUserByEmail(config.GetDefaultValue()),
  105. sessionHistory: encoding.NewSessionHistory(),
  106. secure: config.SecureEncryptionOnly,
  107. }
  108. for _, user := range config.User {
  109. mUser, err := user.ToMemoryUser()
  110. if err != nil {
  111. return nil, newError("failed to get VMess user").Base(err)
  112. }
  113. if err := handler.AddUser(ctx, mUser); err != nil {
  114. return nil, newError("failed to initiate user").Base(err)
  115. }
  116. }
  117. return handler, nil
  118. }
  119. // Close implements common.Closable.
  120. func (h *Handler) Close() error {
  121. return errors.Combine(
  122. h.clients.Close(),
  123. h.sessionHistory.Close(),
  124. common.Close(h.usersByEmail))
  125. }
  126. // Network implements proxy.Inbound.Network().
  127. func (*Handler) Network() []net.Network {
  128. return []net.Network{net.Network_TCP}
  129. }
  130. func (h *Handler) GetUser(email string) *protocol.MemoryUser {
  131. user, existing := h.usersByEmail.Get(email)
  132. if !existing {
  133. h.clients.Add(user)
  134. }
  135. return user
  136. }
  137. func (h *Handler) AddUser(ctx context.Context, user *protocol.MemoryUser) error {
  138. if len(user.Email) > 0 && !h.usersByEmail.Add(user) {
  139. return newError("User ", user.Email, " already exists.")
  140. }
  141. return h.clients.Add(user)
  142. }
  143. func (h *Handler) RemoveUser(ctx context.Context, email string) error {
  144. if len(email) == 0 {
  145. return newError("Email must not be empty.")
  146. }
  147. if !h.usersByEmail.Remove(email) {
  148. return newError("User ", email, " not found.")
  149. }
  150. h.clients.Remove(email)
  151. return nil
  152. }
  153. func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSession, request *protocol.RequestHeader, response *protocol.ResponseHeader, input buf.Reader, output *buf.BufferedWriter) error {
  154. session.EncodeResponseHeader(response, output)
  155. bodyWriter := session.EncodeResponseBody(request, output)
  156. {
  157. // Optimize for small response packet
  158. data, err := input.ReadMultiBuffer()
  159. if err != nil {
  160. return err
  161. }
  162. if err := bodyWriter.WriteMultiBuffer(data); err != nil {
  163. return err
  164. }
  165. }
  166. if err := output.SetBuffered(false); err != nil {
  167. return err
  168. }
  169. if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
  170. return err
  171. }
  172. if request.Option.Has(protocol.RequestOptionChunkStream) {
  173. if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
  174. return err
  175. }
  176. }
  177. return nil
  178. }
  179. func isInsecureEncryption(s protocol.SecurityType) bool {
  180. return s == protocol.SecurityType_NONE || s == protocol.SecurityType_LEGACY || s == protocol.SecurityType_UNKNOWN
  181. }
  182. // Process implements proxy.Inbound.Process().
  183. func (h *Handler) Process(ctx context.Context, network net.Network, connection internet.Connection, dispatcher routing.Dispatcher) error {
  184. sessionPolicy := h.policyManager.ForLevel(0)
  185. if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil {
  186. return newError("unable to set read deadline").Base(err).AtWarning()
  187. }
  188. reader := &buf.BufferedReader{Reader: buf.NewReader(connection)}
  189. svrSession := encoding.NewServerSession(h.clients, h.sessionHistory)
  190. request, err := svrSession.DecodeRequestHeader(reader)
  191. if err != nil {
  192. if errors.Cause(err) != io.EOF {
  193. log.Record(&log.AccessMessage{
  194. From: connection.RemoteAddr(),
  195. To: "",
  196. Status: log.AccessRejected,
  197. Reason: err,
  198. })
  199. err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo()
  200. }
  201. return err
  202. }
  203. if h.secure && isInsecureEncryption(request.Security) {
  204. log.Record(&log.AccessMessage{
  205. From: connection.RemoteAddr(),
  206. To: "",
  207. Status: log.AccessRejected,
  208. Reason: "Insecure encryption",
  209. })
  210. return newError("client is using insecure encryption: ", request.Security)
  211. }
  212. if request.Command != protocol.RequestCommandMux {
  213. log.Record(&log.AccessMessage{
  214. From: connection.RemoteAddr(),
  215. To: request.Destination(),
  216. Status: log.AccessAccepted,
  217. Reason: "",
  218. })
  219. }
  220. newError("received request for ", request.Destination()).WriteToLog(session.ExportIDToError(ctx))
  221. if err := connection.SetReadDeadline(time.Time{}); err != nil {
  222. newError("unable to set back read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx))
  223. }
  224. inbound := session.InboundFromContext(ctx)
  225. if inbound == nil {
  226. panic("no inbound metadata")
  227. }
  228. inbound.User = request.User
  229. sessionPolicy = h.policyManager.ForLevel(request.User.Level)
  230. ctx, cancel := context.WithCancel(ctx)
  231. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  232. ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
  233. link, err := dispatcher.Dispatch(ctx, request.Destination())
  234. if err != nil {
  235. return newError("failed to dispatch request to ", request.Destination()).Base(err)
  236. }
  237. requestDone := func() error {
  238. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  239. bodyReader := svrSession.DecodeRequestBody(request, reader)
  240. if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil {
  241. return newError("failed to transfer request").Base(err)
  242. }
  243. return nil
  244. }
  245. responseDone := func() error {
  246. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  247. writer := buf.NewBufferedWriter(buf.NewWriter(connection))
  248. defer writer.Flush()
  249. response := &protocol.ResponseHeader{
  250. Command: h.generateCommand(ctx, request),
  251. }
  252. return transferResponse(timer, svrSession, request, response, link.Reader, writer)
  253. }
  254. var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer))
  255. if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
  256. common.Interrupt(link.Reader)
  257. common.Interrupt(link.Writer)
  258. return newError("connection ends").Base(err)
  259. }
  260. return nil
  261. }
  262. func (h *Handler) generateCommand(ctx context.Context, request *protocol.RequestHeader) protocol.ResponseCommand {
  263. if h.detours != nil {
  264. tag := h.detours.To
  265. if h.inboundHandlerManager != nil {
  266. handler, err := h.inboundHandlerManager.GetHandler(ctx, tag)
  267. if err != nil {
  268. newError("failed to get detour handler: ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  269. return nil
  270. }
  271. proxyHandler, port, availableMin := handler.GetRandomInboundProxy()
  272. inboundHandler, ok := proxyHandler.(*Handler)
  273. if ok && inboundHandler != nil {
  274. if availableMin > 255 {
  275. availableMin = 255
  276. }
  277. newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WriteToLog(session.ExportIDToError(ctx))
  278. user := inboundHandler.GetUser(request.User.Email)
  279. if user == nil {
  280. return nil
  281. }
  282. account := user.Account.(*vmess.MemoryAccount)
  283. return &protocol.CommandSwitchAccount{
  284. Port: port,
  285. ID: account.ID.UUID(),
  286. AlterIds: uint16(len(account.AlterIDs)),
  287. Level: user.Level,
  288. ValidMin: byte(availableMin),
  289. }
  290. }
  291. }
  292. }
  293. return nil
  294. }
  295. func init() {
  296. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  297. return New(ctx, config.(*Config))
  298. }))
  299. }