github.com/xraypb/xray-core@v1.6.6/proxy/shadowsocks/client.go (about) 1 package shadowsocks 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/xraypb/xray-core/common" 8 "github.com/xraypb/xray-core/common/buf" 9 "github.com/xraypb/xray-core/common/net" 10 "github.com/xraypb/xray-core/common/protocol" 11 "github.com/xraypb/xray-core/common/retry" 12 "github.com/xraypb/xray-core/common/session" 13 "github.com/xraypb/xray-core/common/signal" 14 "github.com/xraypb/xray-core/common/task" 15 "github.com/xraypb/xray-core/core" 16 "github.com/xraypb/xray-core/features/policy" 17 "github.com/xraypb/xray-core/transport" 18 "github.com/xraypb/xray-core/transport/internet" 19 "github.com/xraypb/xray-core/transport/internet/stat" 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 stat.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 ", network, ":", server.Destination().NetAddr()).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 requestDone := func() error { 105 defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) 106 bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) 107 bodyWriter, err := WriteTCPRequest(request, bufferedWriter) 108 if err != nil { 109 return newError("failed to write request").Base(err) 110 } 111 112 if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { 113 return newError("failed to write A request payload").Base(err).AtWarning() 114 } 115 116 if err := bufferedWriter.SetBuffered(false); err != nil { 117 return err 118 } 119 120 return buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)) 121 } 122 123 responseDone := func() error { 124 defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) 125 126 responseReader, err := ReadTCPResponse(user, conn) 127 if err != nil { 128 return err 129 } 130 131 return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer)) 132 } 133 134 responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer)) 135 if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { 136 return newError("connection ends").Base(err) 137 } 138 139 return nil 140 } 141 142 if request.Command == protocol.RequestCommandUDP { 143 144 requestDone := func() error { 145 defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) 146 147 writer := &UDPWriter{ 148 Writer: conn, 149 Request: request, 150 } 151 152 if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil { 153 return newError("failed to transport all UDP request").Base(err) 154 } 155 return nil 156 } 157 158 responseDone := func() error { 159 defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) 160 161 reader := &UDPReader{ 162 Reader: conn, 163 User: user, 164 } 165 166 if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil { 167 return newError("failed to transport all UDP response").Base(err) 168 } 169 return nil 170 } 171 172 responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer)) 173 if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { 174 return newError("connection ends").Base(err) 175 } 176 177 return nil 178 } 179 180 return nil 181 } 182 183 func init() { 184 common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 185 return NewClient(ctx, config.(*ClientConfig)) 186 })) 187 }