inbound.go 4.6 KB

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