github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/proxy/shadowsocks/client.go (about)

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