outbound.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package outbound
  2. import (
  3. "context"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "hash/crc64"
  7. "time"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/buf"
  10. "github.com/xtls/xray-core/common/errors"
  11. "github.com/xtls/xray-core/common/net"
  12. "github.com/xtls/xray-core/common/platform"
  13. "github.com/xtls/xray-core/common/protocol"
  14. "github.com/xtls/xray-core/common/retry"
  15. "github.com/xtls/xray-core/common/session"
  16. "github.com/xtls/xray-core/common/signal"
  17. "github.com/xtls/xray-core/common/task"
  18. "github.com/xtls/xray-core/common/xudp"
  19. core "github.com/xtls/xray-core/core"
  20. "github.com/xtls/xray-core/features/policy"
  21. "github.com/xtls/xray-core/proxy/vmess"
  22. "github.com/xtls/xray-core/proxy/vmess/encoding"
  23. "github.com/xtls/xray-core/transport"
  24. "github.com/xtls/xray-core/transport/internet"
  25. "github.com/xtls/xray-core/transport/internet/stat"
  26. )
  27. // Handler is an outbound connection handler for VMess protocol.
  28. type Handler struct {
  29. serverList *protocol.ServerList
  30. serverPicker protocol.ServerPicker
  31. policyManager policy.Manager
  32. cone bool
  33. }
  34. // New creates a new VMess outbound handler.
  35. func New(ctx context.Context, config *Config) (*Handler, error) {
  36. serverList := protocol.NewServerList()
  37. for _, rec := range config.Receiver {
  38. s, err := protocol.NewServerSpecFromPB(rec)
  39. if err != nil {
  40. return nil, errors.New("failed to parse server spec").Base(err)
  41. }
  42. serverList.AddServer(s)
  43. }
  44. v := core.MustFromContext(ctx)
  45. handler := &Handler{
  46. serverList: serverList,
  47. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  48. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  49. cone: ctx.Value("cone").(bool),
  50. }
  51. return handler, nil
  52. }
  53. // Process implements proxy.Outbound.Process().
  54. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  55. outbounds := session.OutboundsFromContext(ctx)
  56. ob := outbounds[len(outbounds)-1]
  57. if !ob.Target.IsValid() {
  58. return errors.New("target not specified").AtError()
  59. }
  60. ob.Name = "vmess"
  61. ob.CanSpliceCopy = 3
  62. var rec *protocol.ServerSpec
  63. var conn stat.Connection
  64. err := retry.ExponentialBackoff(5, 200).On(func() error {
  65. rec = h.serverPicker.PickServer()
  66. rawConn, err := dialer.Dial(ctx, rec.Destination())
  67. if err != nil {
  68. return err
  69. }
  70. conn = rawConn
  71. return nil
  72. })
  73. if err != nil {
  74. return errors.New("failed to find an available destination").Base(err).AtWarning()
  75. }
  76. defer conn.Close()
  77. target := ob.Target
  78. errors.LogInfo(ctx, "tunneling request to ", target, " via ", rec.Destination().NetAddr())
  79. command := protocol.RequestCommandTCP
  80. if target.Network == net.Network_UDP {
  81. command = protocol.RequestCommandUDP
  82. }
  83. if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.cool" {
  84. command = protocol.RequestCommandMux
  85. }
  86. user := rec.PickUser()
  87. request := &protocol.RequestHeader{
  88. Version: encoding.Version,
  89. User: user,
  90. Command: command,
  91. Address: target.Address,
  92. Port: target.Port,
  93. Option: protocol.RequestOptionChunkStream,
  94. }
  95. account := request.User.Account.(*vmess.MemoryAccount)
  96. request.Security = account.Security
  97. if request.Security == protocol.SecurityType_AES128_GCM || request.Security == protocol.SecurityType_NONE || request.Security == protocol.SecurityType_CHACHA20_POLY1305 {
  98. request.Option.Set(protocol.RequestOptionChunkMasking)
  99. }
  100. if shouldEnablePadding(request.Security) && request.Option.Has(protocol.RequestOptionChunkMasking) {
  101. request.Option.Set(protocol.RequestOptionGlobalPadding)
  102. }
  103. if request.Security == protocol.SecurityType_ZERO {
  104. request.Security = protocol.SecurityType_NONE
  105. request.Option.Clear(protocol.RequestOptionChunkStream)
  106. request.Option.Clear(protocol.RequestOptionChunkMasking)
  107. }
  108. if account.AuthenticatedLengthExperiment {
  109. request.Option.Set(protocol.RequestOptionAuthenticatedLength)
  110. }
  111. input := link.Reader
  112. output := link.Writer
  113. hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
  114. hashkdf.Write(account.ID.Bytes())
  115. behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
  116. var newCtx context.Context
  117. var newCancel context.CancelFunc
  118. if session.TimeoutOnlyFromContext(ctx) {
  119. newCtx, newCancel = context.WithCancel(context.Background())
  120. }
  121. session := encoding.NewClientSession(ctx, int64(behaviorSeed))
  122. sessionPolicy := h.policyManager.ForLevel(request.User.Level)
  123. ctx, cancel := context.WithCancel(ctx)
  124. timer := signal.CancelAfterInactivity(ctx, func() {
  125. cancel()
  126. if newCancel != nil {
  127. newCancel()
  128. }
  129. }, sessionPolicy.Timeouts.ConnectionIdle)
  130. if request.Command == protocol.RequestCommandUDP && h.cone && request.Port != 53 && request.Port != 443 {
  131. request.Command = protocol.RequestCommandMux
  132. request.Address = net.DomainAddress("v1.mux.cool")
  133. request.Port = net.Port(666)
  134. }
  135. requestDone := func() error {
  136. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  137. writer := buf.NewBufferedWriter(buf.NewWriter(conn))
  138. if err := session.EncodeRequestHeader(request, writer); err != nil {
  139. return errors.New("failed to encode request").Base(err).AtWarning()
  140. }
  141. bodyWriter, err := session.EncodeRequestBody(request, writer)
  142. if err != nil {
  143. return errors.New("failed to start encoding").Base(err)
  144. }
  145. bodyWriter2 := bodyWriter
  146. if request.Command == protocol.RequestCommandMux && request.Port == 666 {
  147. bodyWriter = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx))
  148. }
  149. if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
  150. return errors.New("failed to write first payload").Base(err)
  151. }
  152. if err := writer.SetBuffered(false); err != nil {
  153. return err
  154. }
  155. if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
  156. return err
  157. }
  158. if request.Option.Has(protocol.RequestOptionChunkStream) && !account.NoTerminationSignal {
  159. if err := bodyWriter2.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
  160. return err
  161. }
  162. }
  163. return nil
  164. }
  165. responseDone := func() error {
  166. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  167. reader := &buf.BufferedReader{Reader: buf.NewReader(conn)}
  168. header, err := session.DecodeResponseHeader(reader)
  169. if err != nil {
  170. return errors.New("failed to read header").Base(err)
  171. }
  172. h.handleCommand(rec.Destination(), header.Command)
  173. bodyReader, err := session.DecodeResponseBody(request, reader)
  174. if err != nil {
  175. return errors.New("failed to start encoding response").Base(err)
  176. }
  177. if request.Command == protocol.RequestCommandMux && request.Port == 666 {
  178. bodyReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: bodyReader})
  179. }
  180. return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
  181. }
  182. if newCtx != nil {
  183. ctx = newCtx
  184. }
  185. responseDonePost := task.OnSuccess(responseDone, task.Close(output))
  186. if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
  187. return errors.New("connection ends").Base(err)
  188. }
  189. return nil
  190. }
  191. var (
  192. enablePadding = false
  193. )
  194. func shouldEnablePadding(s protocol.SecurityType) bool {
  195. return enablePadding || s == protocol.SecurityType_AES128_GCM || s == protocol.SecurityType_CHACHA20_POLY1305 || s == protocol.SecurityType_AUTO
  196. }
  197. func init() {
  198. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  199. return New(ctx, config.(*Config))
  200. }))
  201. const defaultFlagValue = "NOT_DEFINED_AT_ALL"
  202. paddingValue := platform.NewEnvFlag(platform.UseVmessPadding).GetValue(func() string { return defaultFlagValue })
  203. if paddingValue != defaultFlagValue {
  204. enablePadding = true
  205. }
  206. }