outbound.go 4.7 KB

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