outbound.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package outbound
  2. import (
  3. "context"
  4. "runtime"
  5. "time"
  6. "v2ray.com/core/app"
  7. "v2ray.com/core/app/log"
  8. "v2ray.com/core/common"
  9. "v2ray.com/core/common/buf"
  10. "v2ray.com/core/common/errors"
  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. }
  26. func New(ctx context.Context, config *Config) (*Handler, error) {
  27. space := app.SpaceFromContext(ctx)
  28. if space == nil {
  29. return nil, errors.New("VMess|Outbound: No space in context.")
  30. }
  31. serverList := protocol.NewServerList()
  32. for _, rec := range config.Receiver {
  33. serverList.AddServer(protocol.NewServerSpecFromPB(*rec))
  34. }
  35. handler := &Handler{
  36. serverList: serverList,
  37. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  38. }
  39. return handler, nil
  40. }
  41. // Process implements proxy.Outbound.Process().
  42. func (v *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  43. var rec *protocol.ServerSpec
  44. var conn internet.Connection
  45. err := retry.ExponentialBackoff(5, 200).On(func() error {
  46. rec = v.serverPicker.PickServer()
  47. rawConn, err := dialer.Dial(ctx, rec.Destination())
  48. if err != nil {
  49. return err
  50. }
  51. conn = rawConn
  52. return nil
  53. })
  54. if err != nil {
  55. return errors.Base(err).RequireUserAction().Message("VMess|Outbound: Failed to find an available destination.")
  56. }
  57. defer conn.Close()
  58. target, ok := proxy.TargetFromContext(ctx)
  59. if !ok {
  60. return errors.New("VMess|Outbound: Target not specified.")
  61. }
  62. log.Info("VMess|Outbound: Tunneling request to ", target, " via ", rec.Destination())
  63. command := protocol.RequestCommandTCP
  64. if target.Network == net.Network_UDP {
  65. command = protocol.RequestCommandUDP
  66. }
  67. request := &protocol.RequestHeader{
  68. Version: encoding.Version,
  69. User: rec.PickUser(),
  70. Command: command,
  71. Address: target.Address,
  72. Port: target.Port,
  73. Option: protocol.RequestOptionChunkStream,
  74. }
  75. rawAccount, err := request.User.GetTypedAccount()
  76. if err != nil {
  77. return errors.Base(err).RequireUserAction().Message("VMess|Outbound: Failed to get user account.")
  78. }
  79. account := rawAccount.(*vmess.InternalAccount)
  80. request.Security = account.Security
  81. if request.Security.Is(protocol.SecurityType_AES128_GCM) || request.Security.Is(protocol.SecurityType_NONE) || request.Security.Is(protocol.SecurityType_CHACHA20_POLY1305) {
  82. request.Option.Set(protocol.RequestOptionChunkMasking)
  83. }
  84. conn.SetReusable(true)
  85. if conn.Reusable() { // Conn reuse may be disabled on transportation layer
  86. request.Option.Set(protocol.RequestOptionConnectionReuse)
  87. }
  88. input := outboundRay.OutboundInput()
  89. output := outboundRay.OutboundOutput()
  90. session := encoding.NewClientSession(protocol.DefaultIDHash)
  91. ctx, cancel := context.WithCancel(ctx)
  92. timer := signal.CancelAfterInactivity(ctx, cancel, time.Minute*2)
  93. requestDone := signal.ExecuteAsync(func() error {
  94. writer := buf.NewBufferedWriter(conn)
  95. session.EncodeRequestHeader(request, writer)
  96. bodyWriter := session.EncodeRequestBody(request, writer)
  97. firstPayload, err := input.ReadTimeout(time.Millisecond * 500)
  98. if err != nil && err != buf.ErrReadTimeout {
  99. return errors.Base(err).Message("VMess|Outbound: Failed to get first payload.")
  100. }
  101. if !firstPayload.IsEmpty() {
  102. if err := bodyWriter.Write(firstPayload); err != nil {
  103. return errors.Base(err).Message("VMess|Outbound: Failed to write first payload.")
  104. }
  105. firstPayload.Release()
  106. }
  107. writer.SetBuffered(false)
  108. if err := buf.PipeUntilEOF(timer, input, bodyWriter); err != nil {
  109. return err
  110. }
  111. if request.Option.Has(protocol.RequestOptionChunkStream) {
  112. if err := bodyWriter.Write(buf.NewLocal(8)); err != nil {
  113. return err
  114. }
  115. }
  116. return nil
  117. })
  118. responseDone := signal.ExecuteAsync(func() error {
  119. defer output.Close()
  120. reader := buf.NewBufferedReader(conn)
  121. header, err := session.DecodeResponseHeader(reader)
  122. if err != nil {
  123. return err
  124. }
  125. v.handleCommand(rec.Destination(), header.Command)
  126. conn.SetReusable(header.Option.Has(protocol.ResponseOptionConnectionReuse))
  127. reader.SetBuffered(false)
  128. bodyReader := session.DecodeResponseBody(request, reader)
  129. if err := buf.PipeUntilEOF(timer, bodyReader, output); err != nil {
  130. return err
  131. }
  132. return nil
  133. })
  134. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  135. log.Info("VMess|Outbound: Connection ending with ", err)
  136. conn.SetReusable(false)
  137. return err
  138. }
  139. runtime.KeepAlive(timer)
  140. return nil
  141. }
  142. func init() {
  143. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  144. return New(ctx, config.(*Config))
  145. }))
  146. }