client.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package shadowsocks
  2. import (
  3. "v2ray.com/core/app"
  4. "v2ray.com/core/common/buf"
  5. "v2ray.com/core/common/bufio"
  6. "v2ray.com/core/common/log"
  7. v2net "v2ray.com/core/common/net"
  8. "v2ray.com/core/common/protocol"
  9. "v2ray.com/core/common/retry"
  10. "v2ray.com/core/common/signal"
  11. "v2ray.com/core/proxy"
  12. "v2ray.com/core/transport/internet"
  13. "v2ray.com/core/transport/ray"
  14. )
  15. // Client is a inbound handler for Shadowsocks protocol
  16. type Client struct {
  17. serverPicker protocol.ServerPicker
  18. meta *proxy.OutboundHandlerMeta
  19. }
  20. // NewClient create a new Shadowsocks client.
  21. func NewClient(config *ClientConfig, space app.Space, meta *proxy.OutboundHandlerMeta) (*Client, error) {
  22. serverList := protocol.NewServerList()
  23. for _, rec := range config.Server {
  24. serverList.AddServer(protocol.NewServerSpecFromPB(*rec))
  25. }
  26. client := &Client{
  27. serverPicker: protocol.NewRoundRobinServerPicker(serverList),
  28. meta: meta,
  29. }
  30. return client, nil
  31. }
  32. // Dispatch implements OutboundHandler.Dispatch().
  33. func (v *Client) Dispatch(destination v2net.Destination, ray ray.OutboundRay) {
  34. network := destination.Network
  35. var server *protocol.ServerSpec
  36. var conn internet.Connection
  37. err := retry.ExponentialBackoff(5, 100).On(func() error {
  38. server = v.serverPicker.PickServer()
  39. dest := server.Destination()
  40. dest.Network = network
  41. rawConn, err := internet.Dial(v.meta.Address, dest, v.meta.GetDialerOptions())
  42. if err != nil {
  43. return err
  44. }
  45. conn = rawConn
  46. return nil
  47. })
  48. if err != nil {
  49. log.Warning("Shadowsocks|Client: Failed to find an available destination:", err)
  50. return
  51. }
  52. log.Info("Shadowsocks|Client: Tunneling request to ", destination, " via ", server.Destination())
  53. conn.SetReusable(false)
  54. request := &protocol.RequestHeader{
  55. Version: Version,
  56. Address: destination.Address,
  57. Port: destination.Port,
  58. }
  59. if destination.Network == v2net.Network_TCP {
  60. request.Command = protocol.RequestCommandTCP
  61. } else {
  62. request.Command = protocol.RequestCommandUDP
  63. }
  64. user := server.PickUser()
  65. rawAccount, err := user.GetTypedAccount()
  66. if err != nil {
  67. log.Warning("Shadowsocks|Client: Failed to get a valid user account: ", err)
  68. return
  69. }
  70. account := rawAccount.(*ShadowsocksAccount)
  71. request.User = user
  72. if account.OneTimeAuth == Account_Auto || account.OneTimeAuth == Account_Enabled {
  73. request.Option |= RequestOptionOneTimeAuth
  74. }
  75. if request.Command == protocol.RequestCommandTCP {
  76. bufferedWriter := bufio.NewWriter(conn)
  77. bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
  78. if err != nil {
  79. log.Info("Shadowsocks|Client: Failed to write request: ", err)
  80. return
  81. }
  82. bufferedWriter.SetBuffered(false)
  83. requestDone := signal.ExecuteAsync(func() error {
  84. if err := buf.PipeUntilEOF(ray.OutboundInput(), bodyWriter); err != nil {
  85. return err
  86. }
  87. return nil
  88. })
  89. responseDone := signal.ExecuteAsync(func() error {
  90. defer ray.OutboundOutput().Close()
  91. responseReader, err := ReadTCPResponse(user, conn)
  92. if err != nil {
  93. return err
  94. }
  95. if err := buf.PipeUntilEOF(responseReader, ray.OutboundOutput()); err != nil {
  96. return err
  97. }
  98. return nil
  99. })
  100. if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
  101. log.Info("Shadowsocks|Client: Connection ends with ", err)
  102. ray.OutboundInput().CloseError()
  103. ray.OutboundOutput().CloseError()
  104. }
  105. }
  106. if request.Command == protocol.RequestCommandUDP {
  107. writer := &UDPWriter{
  108. Writer: conn,
  109. Request: request,
  110. }
  111. requestDone := signal.ExecuteAsync(func() error {
  112. if err := buf.PipeUntilEOF(ray.OutboundInput(), writer); err != nil {
  113. log.Info("Shadowsocks|Client: Failed to transport all UDP request: ", err)
  114. return err
  115. }
  116. return nil
  117. })
  118. timedReader := v2net.NewTimeOutReader(16, conn)
  119. responseDone := signal.ExecuteAsync(func() error {
  120. defer ray.OutboundOutput().Close()
  121. reader := &UDPReader{
  122. Reader: timedReader,
  123. User: user,
  124. }
  125. if err := buf.PipeUntilEOF(reader, ray.OutboundOutput()); err != nil {
  126. log.Info("Shadowsocks|Client: Failed to transport all UDP response: ", err)
  127. return err
  128. }
  129. return nil
  130. })
  131. if err := signal.ErrorOrFinish2(requestDone, responseDone); err != nil {
  132. log.Info("Shadowsocks|Client: Connection ends with ", err)
  133. ray.OutboundInput().CloseError()
  134. ray.OutboundOutput().CloseError()
  135. }
  136. }
  137. }
  138. // ClientFactory is a OutboundHandlerFactory.
  139. type ClientFactory struct{}
  140. // StreamCapability implements OutboundHandlerFactory.StreamCapability().
  141. func (ClientFactory) StreamCapability() v2net.NetworkList {
  142. return v2net.NetworkList{
  143. Network: []v2net.Network{v2net.Network_TCP},
  144. }
  145. }
  146. // Create implements OutboundHandlerFactory.Create().
  147. func (ClientFactory) Create(space app.Space, rawConfig interface{}, meta *proxy.OutboundHandlerMeta) (proxy.OutboundHandler, error) {
  148. return NewClient(rawConfig.(*ClientConfig), space, meta)
  149. }