outbound.go 4.5 KB

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