outbound.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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, 100).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. log.Warning("VMess|Outbound: Failed to find an available destination:", err)
  57. return err
  58. }
  59. defer conn.Close()
  60. target := proxy.DestinationFromContext(ctx)
  61. log.Info("VMess|Outbound: Tunneling request to ", target, " via ", rec.Destination())
  62. command := protocol.RequestCommandTCP
  63. if target.Network == net.Network_UDP {
  64. command = protocol.RequestCommandUDP
  65. }
  66. request := &protocol.RequestHeader{
  67. Version: encoding.Version,
  68. User: rec.PickUser(),
  69. Command: command,
  70. Address: target.Address,
  71. Port: target.Port,
  72. Option: protocol.RequestOptionChunkStream,
  73. }
  74. rawAccount, err := request.User.GetTypedAccount()
  75. if err != nil {
  76. log.Warning("VMess|Outbound: Failed to get user account: ", err)
  77. return err
  78. }
  79. account := rawAccount.(*vmess.InternalAccount)
  80. request.Security = account.Security
  81. conn.SetReusable(true)
  82. if conn.Reusable() { // Conn reuse may be disabled on transportation layer
  83. request.Option.Set(protocol.RequestOptionConnectionReuse)
  84. }
  85. input := outboundRay.OutboundInput()
  86. output := outboundRay.OutboundOutput()
  87. session := encoding.NewClientSession(protocol.DefaultIDHash)
  88. ctx, cancel := context.WithCancel(ctx)
  89. timer := signal.CancelAfterInactivity(ctx, cancel, time.Minute*2)
  90. requestDone := signal.ExecuteAsync(func() error {
  91. writer := bufio.NewWriter(conn)
  92. session.EncodeRequestHeader(request, writer)
  93. bodyWriter := session.EncodeRequestBody(request, writer)
  94. firstPayload, err := input.ReadTimeout(time.Millisecond * 500)
  95. if err != nil && err != ray.ErrReadTimeout {
  96. return errors.Base(err).Message("VMess|Outbound: Failed to get first payload.")
  97. }
  98. if !firstPayload.IsEmpty() {
  99. if err := bodyWriter.Write(firstPayload); err != nil {
  100. return errors.Base(err).Message("VMess|Outbound: Failed to write first payload.")
  101. }
  102. firstPayload.Release()
  103. }
  104. writer.SetBuffered(false)
  105. if err := buf.PipeUntilEOF(timer, input, bodyWriter); err != nil {
  106. return err
  107. }
  108. if request.Option.Has(protocol.RequestOptionChunkStream) {
  109. if err := bodyWriter.Write(buf.NewLocal(8)); err != nil {
  110. return err
  111. }
  112. }
  113. return nil
  114. })
  115. responseDone := signal.ExecuteAsync(func() error {
  116. defer output.Close()
  117. reader := bufio.NewReader(conn)
  118. header, err := session.DecodeResponseHeader(reader)
  119. if err != nil {
  120. return err
  121. }
  122. v.handleCommand(rec.Destination(), header.Command)
  123. conn.SetReusable(header.Option.Has(protocol.ResponseOptionConnectionReuse))
  124. reader.SetBuffered(false)
  125. bodyReader := session.DecodeResponseBody(request, reader)
  126. if err := buf.PipeUntilEOF(timer, bodyReader, output); err != nil {
  127. return err
  128. }
  129. return nil
  130. })
  131. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  132. log.Info("VMess|Outbound: Connection ending with ", err)
  133. conn.SetReusable(false)
  134. return err
  135. }
  136. runtime.KeepAlive(timer)
  137. return nil
  138. }
  139. func init() {
  140. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  141. return New(ctx, config.(*Config))
  142. }))
  143. }