client.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // +build !confonly
  2. package trojan
  3. import (
  4. "context"
  5. "time"
  6. "v2ray.com/core"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/net"
  10. "v2ray.com/core/common/protocol"
  11. "v2ray.com/core/common/retry"
  12. "v2ray.com/core/common/session"
  13. "v2ray.com/core/common/signal"
  14. "v2ray.com/core/common/task"
  15. "v2ray.com/core/features/policy"
  16. "v2ray.com/core/transport"
  17. "v2ray.com/core/transport/internet"
  18. "v2ray.com/core/transport/internet/xtls"
  19. )
  20. // Client is a inbound handler for trojan protocol
  21. type Client struct {
  22. serverPicker protocol.ServerPicker
  23. policyManager policy.Manager
  24. }
  25. // NewClient create a new trojan client.
  26. func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
  27. serverList := protocol.NewServerList()
  28. for _, rec := range config.Server {
  29. s, err := protocol.NewServerSpecFromPB(rec)
  30. if err != nil {
  31. return nil, newError("failed to parse server spec").Base(err)
  32. }
  33. serverList.AddServer(s)
  34. }
  35. if serverList.Size() == 0 {
  36. return nil, newError("0 server")
  37. }
  38. v := core.MustFromContext(ctx)
  39. client := &Client{
  40. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  41. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  42. }
  43. return client, nil
  44. }
  45. // Process implements OutboundHandler.Process().
  46. func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  47. outbound := session.OutboundFromContext(ctx)
  48. if outbound == nil || !outbound.Target.IsValid() {
  49. return newError("target not specified")
  50. }
  51. destination := outbound.Target
  52. network := destination.Network
  53. var server *protocol.ServerSpec
  54. var conn internet.Connection
  55. err := retry.ExponentialBackoff(5, 100).On(func() error {
  56. server = c.serverPicker.PickServer()
  57. rawConn, err := dialer.Dial(ctx, server.Destination())
  58. if err != nil {
  59. return err
  60. }
  61. conn = rawConn
  62. return nil
  63. })
  64. if err != nil {
  65. return newError("failed to find an available destination").AtWarning().Base(err)
  66. }
  67. newError("tunneling request to ", destination, " via ", server.Destination()).WriteToLog(session.ExportIDToError(ctx))
  68. defer conn.Close()
  69. user := server.PickUser()
  70. account, ok := user.Account.(*MemoryAccount)
  71. if !ok {
  72. return newError("user account is not valid")
  73. }
  74. iConn := conn
  75. if statConn, ok := iConn.(*internet.StatCouterConnection); ok {
  76. iConn = statConn.Connection
  77. }
  78. connWriter := &ConnWriter{}
  79. allowUDP443 := false
  80. switch account.Flow {
  81. case XRO + "-udp443", XRD + "-udp443":
  82. allowUDP443 = true
  83. account.Flow = account.Flow[:16]
  84. fallthrough
  85. case XRO, XRD:
  86. if destination.Address.Family().IsDomain() && destination.Address.Domain() == muxCoolAddress {
  87. return newError(account.Flow + " doesn't support Mux").AtWarning()
  88. }
  89. if destination.Network == net.Network_UDP {
  90. if !allowUDP443 && destination.Port == 443 {
  91. return newError(account.Flow + " stopped UDP/443").AtInfo()
  92. }
  93. } else { // enable XTLS only if making TCP request
  94. if xtlsConn, ok := iConn.(*xtls.Conn); ok {
  95. xtlsConn.RPRX = true
  96. connWriter.Flow = account.Flow
  97. if account.Flow == XRD {
  98. xtlsConn.DirectMode = true
  99. }
  100. } else {
  101. return newError(`failed to use ` + account.Flow + `, maybe "security" is not "xtls"`).AtWarning()
  102. }
  103. }
  104. case "":
  105. if _, ok := iConn.(*xtls.Conn); ok {
  106. panic(`To avoid misunderstanding, you must fill in Trojan "flow" when using XTLS.`)
  107. }
  108. default:
  109. return newError("unsupported flow " + account.Flow).AtWarning()
  110. }
  111. sessionPolicy := c.policyManager.ForLevel(user.Level)
  112. ctx, cancel := context.WithCancel(ctx)
  113. timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
  114. postRequest := func() error {
  115. defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
  116. var bodyWriter buf.Writer
  117. bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
  118. connWriter.Writer = bufferWriter
  119. connWriter.Target = destination
  120. connWriter.Account = account
  121. if destination.Network == net.Network_UDP {
  122. bodyWriter = &PacketWriter{Writer: connWriter, Target: destination}
  123. } else {
  124. bodyWriter = connWriter
  125. }
  126. // write some request payload to buffer
  127. if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
  128. return newError("failed to write A reqeust payload").Base(err).AtWarning()
  129. }
  130. // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer
  131. if err = bufferWriter.SetBuffered(false); err != nil {
  132. return newError("failed to flush payload").Base(err).AtWarning()
  133. }
  134. if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil {
  135. return newError("failed to transfer request payload").Base(err).AtInfo()
  136. }
  137. return nil
  138. }
  139. getResponse := func() error {
  140. defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
  141. var reader buf.Reader
  142. if network == net.Network_UDP {
  143. reader = &PacketReader{
  144. Reader: conn,
  145. }
  146. } else {
  147. reader = buf.NewReader(conn)
  148. }
  149. return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
  150. }
  151. var responseDoneAndCloseWriter = task.OnSuccess(getResponse, task.Close(link.Writer))
  152. if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
  153. return newError("connection ends").Base(err)
  154. }
  155. return nil
  156. }
  157. func init() {
  158. common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  159. return NewClient(ctx, config.(*ClientConfig))
  160. }))
  161. }