github.com/imannamdari/v2ray-core/v5@v5.0.5/proxy/shadowsocks/client.go (about)

     1  package shadowsocks
     2  
     3  import (
     4  	"context"
     5  
     6  	core "github.com/imannamdari/v2ray-core/v5"
     7  	"github.com/imannamdari/v2ray-core/v5/common"
     8  	"github.com/imannamdari/v2ray-core/v5/common/buf"
     9  	"github.com/imannamdari/v2ray-core/v5/common/net"
    10  	"github.com/imannamdari/v2ray-core/v5/common/net/packetaddr"
    11  	"github.com/imannamdari/v2ray-core/v5/common/protocol"
    12  	"github.com/imannamdari/v2ray-core/v5/common/retry"
    13  	"github.com/imannamdari/v2ray-core/v5/common/session"
    14  	"github.com/imannamdari/v2ray-core/v5/common/signal"
    15  	"github.com/imannamdari/v2ray-core/v5/common/task"
    16  	"github.com/imannamdari/v2ray-core/v5/features/policy"
    17  	"github.com/imannamdari/v2ray-core/v5/proxy"
    18  	"github.com/imannamdari/v2ray-core/v5/transport"
    19  	"github.com/imannamdari/v2ray-core/v5/transport/internet"
    20  	"github.com/imannamdari/v2ray-core/v5/transport/internet/udp"
    21  )
    22  
    23  // Client is a inbound handler for Shadowsocks protocol
    24  type Client struct {
    25  	serverPicker  protocol.ServerPicker
    26  	policyManager policy.Manager
    27  }
    28  
    29  // NewClient create a new Shadowsocks client.
    30  func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
    31  	serverList := protocol.NewServerList()
    32  	for _, rec := range config.Server {
    33  		s, err := protocol.NewServerSpecFromPB(rec)
    34  		if err != nil {
    35  			return nil, newError("failed to parse server spec").Base(err)
    36  		}
    37  		serverList.AddServer(s)
    38  	}
    39  	if serverList.Size() == 0 {
    40  		return nil, newError("0 server")
    41  	}
    42  
    43  	v := core.MustFromContext(ctx)
    44  	client := &Client{
    45  		serverPicker:  protocol.NewRoundRobinServerPicker(serverList),
    46  		policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
    47  	}
    48  	return client, nil
    49  }
    50  
    51  // Process implements OutboundHandler.Process().
    52  func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
    53  	outbound := session.OutboundFromContext(ctx)
    54  	if outbound == nil || !outbound.Target.IsValid() {
    55  		return newError("target not specified")
    56  	}
    57  	destination := outbound.Target
    58  	network := destination.Network
    59  
    60  	var server *protocol.ServerSpec
    61  	var conn internet.Connection
    62  
    63  	err := retry.ExponentialBackoff(5, 100).On(func() error {
    64  		server = c.serverPicker.PickServer()
    65  		dest := server.Destination()
    66  		dest.Network = network
    67  		rawConn, err := dialer.Dial(ctx, dest)
    68  		if err != nil {
    69  			return err
    70  		}
    71  		conn = rawConn
    72  
    73  		return nil
    74  	})
    75  	if err != nil {
    76  		return newError("failed to find an available destination").AtWarning().Base(err)
    77  	}
    78  	newError("tunneling request to ", destination, " via ", network, ":", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx))
    79  
    80  	defer conn.Close()
    81  
    82  	request := &protocol.RequestHeader{
    83  		Version: Version,
    84  		Address: destination.Address,
    85  		Port:    destination.Port,
    86  	}
    87  	if destination.Network == net.Network_TCP {
    88  		request.Command = protocol.RequestCommandTCP
    89  	} else {
    90  		request.Command = protocol.RequestCommandUDP
    91  	}
    92  
    93  	user := server.PickUser()
    94  	_, ok := user.Account.(*MemoryAccount)
    95  	if !ok {
    96  		return newError("user account is not valid")
    97  	}
    98  	request.User = user
    99  
   100  	sessionPolicy := c.policyManager.ForLevel(user.Level)
   101  	ctx, cancel := context.WithCancel(ctx)
   102  	timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
   103  
   104  	if packetConn, err := packetaddr.ToPacketAddrConn(link, destination); err == nil {
   105  		requestDone := func() error {
   106  			protocolWriter := &UDPWriter{
   107  				Writer:  conn,
   108  				Request: request,
   109  			}
   110  			return udp.CopyPacketConn(protocolWriter, packetConn, udp.UpdateActivity(timer))
   111  		}
   112  		responseDone := func() error {
   113  			protocolReader := &UDPReader{
   114  				Reader: conn,
   115  				User:   user,
   116  			}
   117  			return udp.CopyPacketConn(packetConn, protocolReader, udp.UpdateActivity(timer))
   118  		}
   119  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   120  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   121  			return newError("connection ends").Base(err)
   122  		}
   123  		return nil
   124  	}
   125  
   126  	if request.Command == protocol.RequestCommandTCP {
   127  		requestDone := func() error {
   128  			defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   129  			bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn))
   130  			bodyWriter, err := WriteTCPRequest(request, bufferedWriter)
   131  			if err != nil {
   132  				return newError("failed to write request").Base(err)
   133  			}
   134  
   135  			if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, proxy.FirstPayloadTimeout); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout {
   136  				return newError("failed to write A request payload").Base(err).AtWarning()
   137  			}
   138  
   139  			if err := bufferedWriter.SetBuffered(false); err != nil {
   140  				return err
   141  			}
   142  
   143  			return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer))
   144  		}
   145  
   146  		responseDone := func() error {
   147  			defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   148  
   149  			responseReader, err := ReadTCPResponse(user, conn)
   150  			if err != nil {
   151  				return err
   152  			}
   153  
   154  			return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
   155  		}
   156  
   157  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   158  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   159  			return newError("connection ends").Base(err)
   160  		}
   161  
   162  		return nil
   163  	}
   164  
   165  	if request.Command == protocol.RequestCommandUDP {
   166  		writer := &buf.SequentialWriter{Writer: &UDPWriter{
   167  			Writer:  conn,
   168  			Request: request,
   169  		}}
   170  
   171  		requestDone := func() error {
   172  			defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
   173  
   174  			if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil {
   175  				return newError("failed to transport all UDP request").Base(err)
   176  			}
   177  			return nil
   178  		}
   179  
   180  		responseDone := func() error {
   181  			defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
   182  
   183  			reader := &UDPReader{
   184  				Reader: conn,
   185  				User:   user,
   186  			}
   187  
   188  			if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil {
   189  				return newError("failed to transport all UDP response").Base(err)
   190  			}
   191  			return nil
   192  		}
   193  
   194  		responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
   195  		if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
   196  			return newError("connection ends").Base(err)
   197  		}
   198  
   199  		return nil
   200  	}
   201  
   202  	return nil
   203  }
   204  
   205  func init() {
   206  	common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
   207  		return NewClient(ctx, config.(*ClientConfig))
   208  	}))
   209  }