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. )
  18. // Inbound connection handler that handles messages in VMess format.
  19. type VMessInboundHandler struct {
  20. sync.Mutex
  21. space app.Space
  22. clients protocol.UserSet
  23. accepting bool
  24. listener *net.TCPListener
  25. }
  26. func NewVMessInboundHandler(space app.Space, clients protocol.UserSet) *VMessInboundHandler {
  27. return &VMessInboundHandler{
  28. space: space,
  29. clients: clients,
  30. }
  31. }
  32. func (this *VMessInboundHandler) Close() {
  33. this.accepting = false
  34. if this.listener != nil {
  35. this.listener.Close()
  36. this.Lock()
  37. this.listener = nil
  38. this.Unlock()
  39. }
  40. }
  41. func (this *VMessInboundHandler) AddUser(user vmess.User) {
  42. }
  43. func (this *VMessInboundHandler) Listen(port v2net.Port) error {
  44. listener, err := net.ListenTCP("tcp", &net.TCPAddr{
  45. IP: []byte{0, 0, 0, 0},
  46. Port: int(port),
  47. Zone: "",
  48. })
  49. if err != nil {
  50. log.Error("Unable to listen tcp port ", port, ": ", err)
  51. return err
  52. }
  53. this.accepting = true
  54. this.Lock()
  55. this.listener = listener
  56. this.Unlock()
  57. go this.AcceptConnections()
  58. return nil
  59. }
  60. func (this *VMessInboundHandler) AcceptConnections() error {
  61. for this.accepting {
  62. retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  63. this.Lock()
  64. defer this.Unlock()
  65. if !this.accepting {
  66. return nil
  67. }
  68. connection, err := this.listener.AcceptTCP()
  69. if err != nil {
  70. log.Error("Failed to accpet connection: ", err)
  71. return err
  72. }
  73. go this.HandleConnection(connection)
  74. return nil
  75. })
  76. }
  77. return nil
  78. }
  79. func (this *VMessInboundHandler) HandleConnection(connection *net.TCPConn) error {
  80. defer connection.Close()
  81. connReader := v2net.NewTimeOutReader(16, connection)
  82. requestReader := protocol.NewVMessRequestReader(this.clients)
  83. request, err := requestReader.Read(connReader)
  84. if err != nil {
  85. log.Access(connection.RemoteAddr().String(), "", log.AccessRejected, err.Error())
  86. log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
  87. return err
  88. }
  89. log.Access(connection.RemoteAddr().String(), request.Address.String(), log.AccessAccepted, "")
  90. log.Debug("VMessIn: Received request for ", request.Address)
  91. ray := this.space.PacketDispatcher().DispatchToOutbound(v2net.NewPacket(request.Destination(), nil, true))
  92. input := ray.InboundInput()
  93. output := ray.InboundOutput()
  94. var readFinish, writeFinish sync.Mutex
  95. readFinish.Lock()
  96. writeFinish.Lock()
  97. userSettings := vmess.GetUserSettings(request.User.Level)
  98. connReader.SetTimeOut(userSettings.PayloadReadTimeout)
  99. go handleInput(request, connReader, input, &readFinish)
  100. responseKey := md5.Sum(request.RequestKey)
  101. responseIV := md5.Sum(request.RequestIV)
  102. aesStream, err := v2crypto.NewAesEncryptionStream(responseKey[:], responseIV[:])
  103. if err != nil {
  104. log.Error("VMessIn: Failed to create AES decryption stream: ", err)
  105. close(input)
  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: ", 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 := protocol.NewTimedUserSet()
  146. for _, user := range config.AllowedUsers {
  147. allowedClients.AddUser(user)
  148. }
  149. return NewVMessInboundHandler(space, allowedClients), nil
  150. })
  151. }