inbound.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package inbound
  2. import (
  3. "crypto/md5"
  4. "io"
  5. "net"
  6. "sync"
  7. "github.com/v2ray/v2ray-core/app"
  8. "github.com/v2ray/v2ray-core/common/alloc"
  9. v2crypto "github.com/v2ray/v2ray-core/common/crypto"
  10. "github.com/v2ray/v2ray-core/common/log"
  11. v2net "github.com/v2ray/v2ray-core/common/net"
  12. "github.com/v2ray/v2ray-core/common/retry"
  13. "github.com/v2ray/v2ray-core/proxy"
  14. "github.com/v2ray/v2ray-core/proxy/internal"
  15. "github.com/v2ray/v2ray-core/proxy/vmess"
  16. "github.com/v2ray/v2ray-core/proxy/vmess/protocol"
  17. "github.com/v2ray/v2ray-core/proxy/vmess/protocol/user"
  18. )
  19. // Inbound connection handler that handles messages in VMess format.
  20. type VMessInboundHandler struct {
  21. sync.Mutex
  22. space app.Space
  23. clients user.UserSet
  24. accepting bool
  25. listener *net.TCPListener
  26. }
  27. func NewVMessInboundHandler(space app.Space, clients user.UserSet) *VMessInboundHandler {
  28. return &VMessInboundHandler{
  29. space: space,
  30. clients: clients,
  31. }
  32. }
  33. func (this *VMessInboundHandler) Close() {
  34. this.accepting = false
  35. if this.listener != nil {
  36. this.listener.Close()
  37. this.Lock()
  38. this.listener = nil
  39. this.Unlock()
  40. }
  41. }
  42. func (this *VMessInboundHandler) AddUser(user vmess.User) {
  43. }
  44. func (this *VMessInboundHandler) Listen(port v2net.Port) error {
  45. listener, err := net.ListenTCP("tcp", &net.TCPAddr{
  46. IP: []byte{0, 0, 0, 0},
  47. Port: int(port),
  48. Zone: "",
  49. })
  50. if err != nil {
  51. log.Error("Unable to listen tcp port %d: %v", port, err)
  52. return err
  53. }
  54. this.accepting = true
  55. this.Lock()
  56. this.listener = listener
  57. this.Unlock()
  58. go this.AcceptConnections()
  59. return nil
  60. }
  61. func (this *VMessInboundHandler) AcceptConnections() error {
  62. for this.accepting {
  63. retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  64. this.Lock()
  65. defer this.Unlock()
  66. if !this.accepting {
  67. return nil
  68. }
  69. connection, err := this.listener.AcceptTCP()
  70. if err != nil {
  71. log.Error("Failed to accpet connection: %s", err.Error())
  72. return err
  73. }
  74. go this.HandleConnection(connection)
  75. return nil
  76. })
  77. }
  78. return nil
  79. }
  80. func (this *VMessInboundHandler) HandleConnection(connection *net.TCPConn) error {
  81. defer connection.Close()
  82. connReader := v2net.NewTimeOutReader(16, connection)
  83. requestReader := protocol.NewVMessRequestReader(this.clients)
  84. request, err := requestReader.Read(connReader)
  85. if err != nil {
  86. log.Access(connection.RemoteAddr().String(), "", log.AccessRejected, err.Error())
  87. log.Warning("VMessIn: Invalid request from (%s): %v", connection.RemoteAddr().String(), err)
  88. return err
  89. }
  90. log.Access(connection.RemoteAddr().String(), request.Address.String(), log.AccessAccepted, "")
  91. log.Debug("VMessIn: Received request for %s", request.Address.String())
  92. ray := this.space.PacketDispatcher().DispatchToOutbound(v2net.NewPacket(request.Destination(), nil, true))
  93. input := ray.InboundInput()
  94. output := ray.InboundOutput()
  95. var readFinish, writeFinish sync.Mutex
  96. readFinish.Lock()
  97. writeFinish.Lock()
  98. userSettings := vmess.GetUserSettings(request.User.Level())
  99. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  100. go handleInput(request, connReader, input, &readFinish)
  101. responseKey := md5.Sum(request.RequestKey)
  102. responseIV := md5.Sum(request.RequestIV)
  103. aesStream, err := v2crypto.NewAesEncryptionStream(responseKey[:], responseIV[:])
  104. if err != nil {
  105. log.Error("VMessIn: Failed to create AES decryption stream: %v", err)
  106. return err
  107. }
  108. responseWriter := v2crypto.NewCryptionWriter(aesStream, connection)
  109. // Optimize for small response packet
  110. buffer := alloc.NewLargeBuffer().Clear()
  111. defer buffer.Release()
  112. buffer.AppendBytes(request.ResponseHeader[0] ^ request.ResponseHeader[1])
  113. buffer.AppendBytes(request.ResponseHeader[2] ^ request.ResponseHeader[3])
  114. buffer.AppendBytes(byte(0), byte(0))
  115. if data, open := <-output; open {
  116. buffer.Append(data.Value)
  117. data.Release()
  118. responseWriter.Write(buffer.Value)
  119. go handleOutput(request, responseWriter, output, &writeFinish)
  120. writeFinish.Lock()
  121. }
  122. connection.CloseWrite()
  123. readFinish.Lock()
  124. return nil
  125. }
  126. func handleInput(request *protocol.VMessRequest, reader io.Reader, input chan<- *alloc.Buffer, finish *sync.Mutex) {
  127. defer close(input)
  128. defer finish.Unlock()
  129. aesStream, err := v2crypto.NewAesDecryptionStream(request.RequestKey, request.RequestIV)
  130. if err != nil {
  131. log.Error("VMessIn: Failed to create AES decryption stream: %v", err)
  132. return
  133. }
  134. requestReader := v2crypto.NewCryptionReader(aesStream, reader)
  135. v2net.ReaderToChan(input, requestReader)
  136. }
  137. func handleOutput(request *protocol.VMessRequest, writer io.Writer, output <-chan *alloc.Buffer, finish *sync.Mutex) {
  138. v2net.ChanToWriter(writer, output)
  139. finish.Unlock()
  140. }
  141. func init() {
  142. internal.MustRegisterInboundConnectionHandlerCreator("vmess",
  143. func(space app.Space, rawConfig interface{}) (proxy.InboundConnectionHandler, error) {
  144. config := rawConfig.(Config)
  145. allowedClients := user.NewTimedUserSet()
  146. for _, user := range config.AllowedUsers() {
  147. allowedClients.AddUser(user)
  148. }
  149. return NewVMessInboundHandler(space, allowedClients), nil
  150. })
  151. }