inbound.go 4.6 KB

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