outbound.go 4.7 KB

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