outbound.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package outbound
  2. //go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg outbound -path Proxy,VMess,Outbound
  3. import (
  4. "context"
  5. "time"
  6. "v2ray.com/core/app"
  7. "v2ray.com/core/app/log"
  8. "v2ray.com/core/app/policy"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/buf"
  11. "v2ray.com/core/common/net"
  12. "v2ray.com/core/common/protocol"
  13. "v2ray.com/core/common/retry"
  14. "v2ray.com/core/common/signal"
  15. "v2ray.com/core/proxy"
  16. "v2ray.com/core/proxy/vmess"
  17. "v2ray.com/core/proxy/vmess/encoding"
  18. "v2ray.com/core/transport/internet"
  19. "v2ray.com/core/transport/ray"
  20. )
  21. // Handler is an outbound connection handler for VMess protocol.
  22. type Handler struct {
  23. serverList *protocol.ServerList
  24. serverPicker protocol.ServerPicker
  25. policyManager policy.Manager
  26. }
  27. func New(ctx context.Context, config *Config) (*Handler, error) {
  28. space := app.SpaceFromContext(ctx)
  29. if space == nil {
  30. return nil, newError("no space in context.")
  31. }
  32. serverList := protocol.NewServerList()
  33. for _, rec := range config.Receiver {
  34. serverList.AddServer(protocol.NewServerSpecFromPB(*rec))
  35. }
  36. handler := &Handler{
  37. serverList: serverList,
  38. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  39. }
  40. space.On(app.SpaceInitializing, func(interface{}) error {
  41. pm := policy.FromSpace(space)
  42. if pm == nil {
  43. return newError("Policy is not found in space.")
  44. }
  45. handler.policyManager = pm
  46. return nil
  47. })
  48. return handler, nil
  49. }
  50. // Process implements proxy.Outbound.Process().
  51. func (v *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  52. var rec *protocol.ServerSpec
  53. var conn internet.Connection
  54. err := retry.ExponentialBackoff(5, 200).On(func() error {
  55. rec = v.serverPicker.PickServer()
  56. rawConn, err := dialer.Dial(ctx, rec.Destination())
  57. if err != nil {
  58. return err
  59. }
  60. conn = rawConn
  61. return nil
  62. })
  63. if err != nil {
  64. return newError("failed to find an available destination").Base(err).AtWarning()
  65. }
  66. defer conn.Close()
  67. target, ok := proxy.TargetFromContext(ctx)
  68. if !ok {
  69. return newError("target not specified").AtError()
  70. }
  71. log.Trace(newError("tunneling request to ", target, " via ", rec.Destination()))
  72. command := protocol.RequestCommandTCP
  73. if target.Network == net.Network_UDP {
  74. command = protocol.RequestCommandUDP
  75. }
  76. if target.Address.Family().IsDomain() && target.Address.Domain() == "v1.mux.com" {
  77. command = protocol.RequestCommandMux
  78. }
  79. request := &protocol.RequestHeader{
  80. Version: encoding.Version,
  81. User: rec.PickUser(),
  82. Command: command,
  83. Address: target.Address,
  84. Port: target.Port,
  85. Option: protocol.RequestOptionChunkStream,
  86. }
  87. rawAccount, err := request.User.GetTypedAccount()
  88. if err != nil {
  89. return newError("failed to get user account").Base(err).AtWarning()
  90. }
  91. account := rawAccount.(*vmess.InternalAccount)
  92. request.Security = account.Security
  93. if request.Security.Is(protocol.SecurityType_AES128_GCM) || request.Security.Is(protocol.SecurityType_NONE) || request.Security.Is(protocol.SecurityType_CHACHA20_POLY1305) {
  94. request.Option.Set(protocol.RequestOptionChunkMasking)
  95. }
  96. input := outboundRay.OutboundInput()
  97. output := outboundRay.OutboundOutput()
  98. session := encoding.NewClientSession(protocol.DefaultIDHash)
  99. sessionPolicy := v.policyManager.GetPolicy(request.User.Level)
  100. ctx, cancel := context.WithCancel(ctx)
  101. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeout.ConnectionIdle.Duration())
  102. requestDone := signal.ExecuteAsync(func() error {
  103. writer := buf.NewBufferedWriter(buf.NewWriter(conn))
  104. if err := session.EncodeRequestHeader(request, writer); err != nil {
  105. return newError("failed to encode request").Base(err).AtWarning()
  106. }
  107. bodyWriter := session.EncodeRequestBody(request, writer)
  108. firstPayload, err := input.ReadTimeout(time.Millisecond * 500)
  109. if err != nil && err != buf.ErrReadTimeout {
  110. return newError("failed to get first payload").Base(err)
  111. }
  112. if !firstPayload.IsEmpty() {
  113. if err := bodyWriter.WriteMultiBuffer(firstPayload); err != nil {
  114. return newError("failed to write first payload").Base(err)
  115. }
  116. firstPayload.Release()
  117. }
  118. if err := writer.SetBuffered(false); err != nil {
  119. return err
  120. }
  121. if err := buf.Copy(input, bodyWriter, buf.UpdateActivity(timer)); err != nil {
  122. return err
  123. }
  124. if request.Option.Has(protocol.RequestOptionChunkStream) {
  125. if err := bodyWriter.WriteMultiBuffer(buf.MultiBuffer{}); err != nil {
  126. return err
  127. }
  128. }
  129. timer.SetTimeout(sessionPolicy.Timeout.DownlinkOnly.Duration())
  130. return nil
  131. })
  132. responseDone := signal.ExecuteAsync(func() error {
  133. defer output.Close()
  134. defer timer.SetTimeout(sessionPolicy.Timeout.UplinkOnly.Duration())
  135. reader := buf.NewBufferedReader(buf.NewReader(conn))
  136. header, err := session.DecodeResponseHeader(reader)
  137. if err != nil {
  138. return err
  139. }
  140. v.handleCommand(rec.Destination(), header.Command)
  141. reader.SetBuffered(false)
  142. bodyReader := session.DecodeResponseBody(request, reader)
  143. return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
  144. })
  145. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  146. return newError("connection ends").Base(err)
  147. }
  148. return nil
  149. }
  150. func init() {
  151. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  152. return New(ctx, config.(*Config))
  153. }))
  154. }