vmessout.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. v2crypto "github.com/v2ray/v2ray-core/common/crypto"
  11. "github.com/v2ray/v2ray-core/common/log"
  12. v2net "github.com/v2ray/v2ray-core/common/net"
  13. "github.com/v2ray/v2ray-core/proxy/common/connhandler"
  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. type VMessOutboundHandler struct {
  20. vNextList []*config.OutboundTarget
  21. vNextListUDP []*config.OutboundTarget
  22. }
  23. func NewVMessOutboundHandler(vNextList, vNextListUDP []*config.OutboundTarget) *VMessOutboundHandler {
  24. return &VMessOutboundHandler{
  25. vNextList: vNextList,
  26. vNextListUDP: vNextListUDP,
  27. }
  28. }
  29. func pickVNext(serverList []*config.OutboundTarget) (v2net.Destination, config.User) {
  30. vNextLen := len(serverList)
  31. if vNextLen == 0 {
  32. panic("VMessOut: Zero vNext is configured.")
  33. }
  34. vNextIndex := 0
  35. if vNextLen > 1 {
  36. vNextIndex = mrand.Intn(vNextLen)
  37. }
  38. vNext := serverList[vNextIndex]
  39. vNextUserLen := len(vNext.Accounts)
  40. if vNextUserLen == 0 {
  41. panic("VMessOut: Zero User account.")
  42. }
  43. vNextUserIndex := 0
  44. if vNextUserLen > 1 {
  45. vNextUserIndex = mrand.Intn(vNextUserLen)
  46. }
  47. vNextUser := vNext.Accounts[vNextUserIndex]
  48. return vNext.Destination, vNextUser
  49. }
  50. func (handler *VMessOutboundHandler) Dispatch(firstPacket v2net.Packet, ray ray.OutboundRay) error {
  51. vNextList := handler.vNextList
  52. if firstPacket.Destination().IsUDP() {
  53. vNextList = handler.vNextListUDP
  54. }
  55. vNextAddress, vNextUser := pickVNext(vNextList)
  56. command := protocol.CmdTCP
  57. if firstPacket.Destination().IsUDP() {
  58. command = protocol.CmdUDP
  59. }
  60. request := &protocol.VMessRequest{
  61. Version: protocol.Version,
  62. User: vNextUser,
  63. Command: command,
  64. Address: firstPacket.Destination().Address(),
  65. }
  66. buffer := alloc.NewSmallBuffer()
  67. defer buffer.Release()
  68. v2net.ReadAllBytes(rand.Reader, buffer.Value[:36]) // 16 + 16 + 4
  69. request.RequestIV = buffer.Value[:16]
  70. request.RequestKey = buffer.Value[16:32]
  71. request.ResponseHeader = buffer.Value[32:36]
  72. return startCommunicate(request, vNextAddress, ray, firstPacket)
  73. }
  74. func startCommunicate(request *protocol.VMessRequest, dest v2net.Destination, ray ray.OutboundRay, firstPacket v2net.Packet) error {
  75. conn, err := net.Dial(dest.Network(), dest.Address().String())
  76. if err != nil {
  77. log.Error("Failed to open %s: %v", dest.String(), err)
  78. if ray != nil {
  79. close(ray.OutboundOutput())
  80. }
  81. return err
  82. }
  83. log.Info("VMessOut: Tunneling request to %s via %s", request.Address.String(), dest.String())
  84. defer conn.Close()
  85. input := ray.OutboundInput()
  86. output := ray.OutboundOutput()
  87. var requestFinish, responseFinish sync.Mutex
  88. requestFinish.Lock()
  89. responseFinish.Lock()
  90. go handleRequest(conn, request, firstPacket, input, &requestFinish)
  91. go handleResponse(conn, request, output, &responseFinish, dest.IsUDP())
  92. requestFinish.Lock()
  93. if tcpConn, ok := conn.(*net.TCPConn); ok {
  94. tcpConn.CloseWrite()
  95. }
  96. responseFinish.Lock()
  97. return nil
  98. }
  99. func handleRequest(conn net.Conn, request *protocol.VMessRequest, firstPacket v2net.Packet, input <-chan *alloc.Buffer, finish *sync.Mutex) {
  100. defer finish.Unlock()
  101. aesStream, err := v2crypto.NewAesEncryptionStream(request.RequestKey[:], request.RequestIV[:])
  102. if err != nil {
  103. log.Error("VMessOut: Failed to create AES encryption stream: %v", err)
  104. return
  105. }
  106. encryptRequestWriter := v2crypto.NewCryptionWriter(aesStream, conn)
  107. buffer := alloc.NewBuffer().Clear()
  108. buffer, err = request.ToBytes(user.NewTimeHash(user.HMACHash{}), user.GenerateRandomInt64InRange, buffer)
  109. if err != nil {
  110. log.Error("VMessOut: Failed to serialize VMess request: %v", err)
  111. return
  112. }
  113. // Send first packet of payload together with request, in favor of small requests.
  114. firstChunk := firstPacket.Chunk()
  115. moreChunks := firstPacket.MoreChunks()
  116. if firstChunk == nil && moreChunks {
  117. firstChunk, moreChunks = <-input
  118. }
  119. if firstChunk != nil {
  120. aesStream.XORKeyStream(firstChunk.Value, firstChunk.Value)
  121. buffer.Append(firstChunk.Value)
  122. firstChunk.Release()
  123. _, err = conn.Write(buffer.Value)
  124. buffer.Release()
  125. if err != nil {
  126. log.Error("VMessOut: Failed to write VMess request: %v", err)
  127. return
  128. }
  129. }
  130. if moreChunks {
  131. v2net.ChanToWriter(encryptRequestWriter, input)
  132. }
  133. return
  134. }
  135. func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- *alloc.Buffer, finish *sync.Mutex, isUDP bool) {
  136. defer finish.Unlock()
  137. defer close(output)
  138. responseKey := md5.Sum(request.RequestKey[:])
  139. responseIV := md5.Sum(request.RequestIV[:])
  140. aesStream, err := v2crypto.NewAesDecryptionStream(responseKey[:], responseIV[:])
  141. if err != nil {
  142. log.Error("VMessOut: Failed to create AES encryption stream: %v", err)
  143. return
  144. }
  145. decryptResponseReader := v2crypto.NewCryptionReader(aesStream, conn)
  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{}) (connhandler.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. connhandler.RegisterOutboundConnectionHandlerFactory("vmess", &VMessOutboundHandlerFactory{})
  181. }