vmessout.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package vmess
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "crypto/rand"
  6. mrand "math/rand"
  7. "net"
  8. "sync"
  9. "github.com/v2ray/v2ray-core/common/alloc"
  10. v2io "github.com/v2ray/v2ray-core/common/io"
  11. "github.com/v2ray/v2ray-core/common/log"
  12. v2net "github.com/v2ray/v2ray-core/common/net"
  13. "github.com/v2ray/v2ray-core/proxy"
  14. "github.com/v2ray/v2ray-core/proxy/vmess/config"
  15. "github.com/v2ray/v2ray-core/proxy/vmess/protocol"
  16. "github.com/v2ray/v2ray-core/proxy/vmess/protocol/user"
  17. "github.com/v2ray/v2ray-core/transport/ray"
  18. )
  19. const (
  20. InfoTimeNotSync = "Please check the User ID in your vmess configuration, and make sure the time on your local and remote server are in sync."
  21. )
  22. type VMessOutboundHandler struct {
  23. vNextList []*config.OutboundTarget
  24. vNextListUDP []*config.OutboundTarget
  25. }
  26. func NewVMessOutboundHandler(vNextList, vNextListUDP []*config.OutboundTarget) *VMessOutboundHandler {
  27. return &VMessOutboundHandler{
  28. vNextList: vNextList,
  29. vNextListUDP: vNextListUDP,
  30. }
  31. }
  32. func pickVNext(serverList []*config.OutboundTarget) (v2net.Destination, config.User) {
  33. vNextLen := len(serverList)
  34. if vNextLen == 0 {
  35. panic("VMessOut: Zero vNext is configured.")
  36. }
  37. vNextIndex := 0
  38. if vNextLen > 1 {
  39. vNextIndex = mrand.Intn(vNextLen)
  40. }
  41. vNext := serverList[vNextIndex]
  42. vNextUserLen := len(vNext.Accounts)
  43. if vNextUserLen == 0 {
  44. panic("VMessOut: Zero User account.")
  45. }
  46. vNextUserIndex := 0
  47. if vNextUserLen > 1 {
  48. vNextUserIndex = mrand.Intn(vNextUserLen)
  49. }
  50. vNextUser := vNext.Accounts[vNextUserIndex]
  51. return vNext.Destination, vNextUser
  52. }
  53. func (handler *VMessOutboundHandler) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
  54. vNextList := handler.vNextList
  55. if firstPacket.Destination().IsUDP() {
  56. vNextList = handler.vNextListUDP
  57. }
  58. vNextAddress, vNextUser := pickVNext(vNextList)
  59. command := protocol.CmdTCP
  60. if firstPacket.Destination().IsUDP() {
  61. command = protocol.CmdUDP
  62. }
  63. request := &protocol.VMessRequest{
  64. Version: protocol.Version,
  65. UserId: *vNextUser.ID(),
  66. Command: command,
  67. Address: firstPacket.Destination().Address(),
  68. }
  69. buffer := make([]byte, 36) // 16 + 16 + 4
  70. rand.Read(buffer)
  71. request.RequestIV = buffer[:16]
  72. request.RequestKey = buffer[16:32]
  73. request.ResponseHeader = buffer[32:]
  74. return startCommunicate(request, vNextAddress, ray, firstPacket)
  75. }
  76. func startCommunicate(request *protocol.VMessRequest, dest v2net.Destination, ray ray.OutboundRay, firstPacket v2net.Packet) error {
  77. conn, err := net.Dial(dest.Network(), dest.Address().String())
  78. if err != nil {
  79. log.Error("Failed to open %s: %v", dest.String(), err)
  80. if ray != nil {
  81. close(ray.OutboundOutput())
  82. }
  83. return err
  84. }
  85. log.Info("VMessOut: Tunneling request to %s via %s", request.Address.String(), dest.String())
  86. defer conn.Close()
  87. input := ray.OutboundInput()
  88. output := ray.OutboundOutput()
  89. var requestFinish, responseFinish sync.Mutex
  90. requestFinish.Lock()
  91. responseFinish.Lock()
  92. go handleRequest(conn, request, firstPacket, input, &requestFinish)
  93. go handleResponse(conn, request, output, &responseFinish, dest.IsUDP())
  94. requestFinish.Lock()
  95. if tcpConn, ok := conn.(*net.TCPConn); ok {
  96. tcpConn.CloseWrite()
  97. }
  98. responseFinish.Lock()
  99. return nil
  100. }
  101. func handleRequest(conn net.Conn, request *protocol.VMessRequest, firstPacket v2net.Packet, input <-chan *alloc.Buffer, finish *sync.Mutex) {
  102. defer finish.Unlock()
  103. encryptRequestWriter, err := v2io.NewAesEncryptWriter(request.RequestKey[:], request.RequestIV[:], conn)
  104. if err != nil {
  105. log.Error("VMessOut: Failed to create encrypt writer: %v", err)
  106. return
  107. }
  108. buffer := alloc.NewBuffer().Clear()
  109. buffer, err = request.ToBytes(user.NewTimeHash(user.HMACHash{}), user.GenerateRandomInt64InRange, buffer)
  110. if err != nil {
  111. log.Error("VMessOut: Failed to serialize VMess request: %v", err)
  112. return
  113. }
  114. // Send first packet of payload together with request, in favor of small requests.
  115. firstChunk := firstPacket.Chunk()
  116. moreChunks := firstPacket.MoreChunks()
  117. if firstChunk == nil && moreChunks {
  118. firstChunk, moreChunks = <-input
  119. }
  120. if firstChunk != nil {
  121. encryptRequestWriter.Crypt(firstChunk.Value)
  122. buffer.Append(firstChunk.Value)
  123. firstChunk.Release()
  124. _, err = conn.Write(buffer.Value)
  125. buffer.Release()
  126. if err != nil {
  127. log.Error("VMessOut: Failed to write VMess request: %v", err)
  128. return
  129. }
  130. }
  131. if moreChunks {
  132. v2net.ChanToWriter(encryptRequestWriter, input)
  133. }
  134. return
  135. }
  136. func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- *alloc.Buffer, finish *sync.Mutex, isUDP bool) {
  137. defer finish.Unlock()
  138. defer close(output)
  139. responseKey := md5.Sum(request.RequestKey[:])
  140. responseIV := md5.Sum(request.RequestIV[:])
  141. decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
  142. if err != nil {
  143. log.Error("VMessOut: Failed to create decrypt reader: %v", err)
  144. return
  145. }
  146. buffer, err := v2net.ReadFrom(decryptResponseReader, nil)
  147. if err != nil {
  148. log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", buffer.Len(), err)
  149. return
  150. }
  151. if buffer.Len() < 4 || !bytes.Equal(buffer.Value[:4], request.ResponseHeader[:]) {
  152. log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.")
  153. return
  154. }
  155. log.Info("VMessOut received %d bytes from %s", buffer.Len()-4, conn.RemoteAddr().String())
  156. buffer.SliceFrom(4)
  157. output <- buffer
  158. if !isUDP {
  159. v2net.ReaderToChan(output, decryptResponseReader)
  160. }
  161. return
  162. }
  163. type VMessOutboundHandlerFactory struct {
  164. }
  165. func (factory *VMessOutboundHandlerFactory) Create(rawConfig interface{}) (proxy.OutboundConnectionHandler, error) {
  166. vOutConfig := rawConfig.(config.Outbound)
  167. servers := make([]*config.OutboundTarget, 0, 16)
  168. udpServers := make([]*config.OutboundTarget, 0, 16)
  169. for _, target := range vOutConfig.Targets() {
  170. if target.Destination.IsTCP() {
  171. servers = append(servers, target)
  172. }
  173. if target.Destination.IsUDP() {
  174. udpServers = append(udpServers, target)
  175. }
  176. }
  177. return NewVMessOutboundHandler(servers, udpServers), nil
  178. }
  179. func init() {
  180. proxy.RegisterOutboundConnectionHandlerFactory("vmess", &VMessOutboundHandlerFactory{})
  181. }