vmessin.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. package vmess
  2. import (
  3. "crypto/md5"
  4. "io"
  5. "net"
  6. "strconv"
  7. "time"
  8. "github.com/v2ray/v2ray-core"
  9. v2io "github.com/v2ray/v2ray-core/common/io"
  10. "github.com/v2ray/v2ray-core/common/log"
  11. v2net "github.com/v2ray/v2ray-core/common/net"
  12. "github.com/v2ray/v2ray-core/proxy/vmess/protocol"
  13. "github.com/v2ray/v2ray-core/proxy/vmess/protocol/user"
  14. )
  15. const (
  16. requestReadTimeOut = 4 * time.Second
  17. )
  18. var (
  19. zeroTime time.Time
  20. )
  21. type VMessInboundHandler struct {
  22. vPoint *core.Point
  23. clients user.UserSet
  24. accepting bool
  25. }
  26. func NewVMessInboundHandler(vp *core.Point, clients user.UserSet) *VMessInboundHandler {
  27. return &VMessInboundHandler{
  28. vPoint: vp,
  29. clients: clients,
  30. }
  31. }
  32. func (handler *VMessInboundHandler) Listen(port uint16) error {
  33. listener, err := net.Listen("tcp", ":"+strconv.Itoa(int(port)))
  34. if err != nil {
  35. return log.Error("Unable to listen tcp:%d", port)
  36. }
  37. handler.accepting = true
  38. go handler.AcceptConnections(listener)
  39. return nil
  40. }
  41. func (handler *VMessInboundHandler) AcceptConnections(listener net.Listener) error {
  42. for handler.accepting {
  43. connection, err := listener.Accept()
  44. if err != nil {
  45. return log.Error("Failed to accpet connection: %s", err.Error())
  46. }
  47. go handler.HandleConnection(connection)
  48. }
  49. return nil
  50. }
  51. func (handler *VMessInboundHandler) HandleConnection(connection net.Conn) error {
  52. defer connection.Close()
  53. reader := protocol.NewVMessRequestReader(handler.clients)
  54. // Timeout 4 seconds to prevent DoS attack
  55. connection.SetReadDeadline(time.Now().Add(requestReadTimeOut))
  56. request, err := reader.Read(connection)
  57. if err != nil {
  58. log.Warning("VMessIn: Invalid request from (%s): %v", connection.RemoteAddr().String(), err)
  59. return err
  60. }
  61. log.Debug("VMessIn: Received request for %s", request.Address.String())
  62. // Clear read timeout
  63. connection.SetReadDeadline(zeroTime)
  64. ray := handler.vPoint.DispatchToOutbound(v2net.NewTCPPacket(request.Destination()))
  65. input := ray.InboundInput()
  66. output := ray.InboundOutput()
  67. readFinish := make(chan bool)
  68. writeFinish := make(chan bool)
  69. go handleInput(request, connection, input, readFinish)
  70. responseKey := md5.Sum(request.RequestKey[:])
  71. responseIV := md5.Sum(request.RequestIV[:])
  72. response := protocol.NewVMessResponse(request)
  73. responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], connection)
  74. if err != nil {
  75. return log.Error("VMessIn: Failed to create encrypt writer: %v", err)
  76. }
  77. // Optimize for small response packet
  78. buffer := make([]byte, 0, 1024)
  79. buffer = append(buffer, response[:]...)
  80. if data, open := <-output; open {
  81. buffer = append(buffer, data...)
  82. responseWriter.Write(buffer)
  83. go handleOutput(request, responseWriter, output, writeFinish)
  84. <-writeFinish
  85. }
  86. if tcpConn, ok := connection.(*net.TCPConn); ok {
  87. tcpConn.CloseWrite()
  88. }
  89. <-readFinish
  90. return nil
  91. }
  92. func handleInput(request *protocol.VMessRequest, reader io.Reader, input chan<- []byte, finish chan<- bool) {
  93. defer close(input)
  94. defer close(finish)
  95. requestReader, err := v2io.NewAesDecryptReader(request.RequestKey[:], request.RequestIV[:], reader)
  96. if err != nil {
  97. log.Error("VMessIn: Failed to create decrypt reader: %v", err)
  98. return
  99. }
  100. v2net.ReaderToChan(input, requestReader)
  101. }
  102. func handleOutput(request *protocol.VMessRequest, writer io.Writer, output <-chan []byte, finish chan<- bool) {
  103. v2net.ChanToWriter(writer, output)
  104. close(finish)
  105. }
  106. type VMessInboundHandlerFactory struct {
  107. }
  108. func (factory *VMessInboundHandlerFactory) Create(vp *core.Point, rawConfig []byte) (core.InboundConnectionHandler, error) {
  109. config, err := loadInboundConfig(rawConfig)
  110. if err != nil {
  111. panic(log.Error("VMessIn: Failed to load VMess inbound config: %v", err))
  112. }
  113. allowedClients := user.NewTimedUserSet()
  114. for _, client := range config.AllowedClients {
  115. user, err := client.ToUser()
  116. if err != nil {
  117. panic(log.Error("VMessIn: Failed to parse user id %s: %v", client.Id, err))
  118. }
  119. allowedClients.AddUser(user)
  120. }
  121. return NewVMessInboundHandler(vp, allowedClients), nil
  122. }
  123. func init() {
  124. core.RegisterInboundConnectionHandlerFactory("vmess", &VMessInboundHandlerFactory{})
  125. }