github.com/v2fly/v2ray-core/v4@v4.45.2/proxy/shadowsocks/client.go (about)

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