github.com/xmplusdev/xray-core@v1.8.10/proxy/socks/client.go (about) 1 package socks 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/xmplusdev/xray-core/common" 8 "github.com/xmplusdev/xray-core/common/buf" 9 "github.com/xmplusdev/xray-core/common/net" 10 "github.com/xmplusdev/xray-core/common/protocol" 11 "github.com/xmplusdev/xray-core/common/retry" 12 "github.com/xmplusdev/xray-core/common/session" 13 "github.com/xmplusdev/xray-core/common/signal" 14 "github.com/xmplusdev/xray-core/common/task" 15 "github.com/xmplusdev/xray-core/core" 16 "github.com/xmplusdev/xray-core/features/dns" 17 "github.com/xmplusdev/xray-core/features/policy" 18 "github.com/xmplusdev/xray-core/transport" 19 "github.com/xmplusdev/xray-core/transport/internet" 20 "github.com/xmplusdev/xray-core/transport/internet/stat" 21 ) 22 23 // Client is a Socks5 client. 24 type Client struct { 25 serverPicker protocol.ServerPicker 26 policyManager policy.Manager 27 version Version 28 dns dns.Client 29 } 30 31 // NewClient create a new Socks5 client based on the given config. 32 func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { 33 serverList := protocol.NewServerList() 34 for _, rec := range config.Server { 35 s, err := protocol.NewServerSpecFromPB(rec) 36 if err != nil { 37 return nil, newError("failed to get server spec").Base(err) 38 } 39 serverList.AddServer(s) 40 } 41 if serverList.Size() == 0 { 42 return nil, newError("0 target server") 43 } 44 45 v := core.MustFromContext(ctx) 46 c := &Client{ 47 serverPicker: protocol.NewRoundRobinServerPicker(serverList), 48 policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), 49 version: config.Version, 50 } 51 if config.Version == Version_SOCKS4 { 52 c.dns = v.GetFeature(dns.ClientType()).(dns.Client) 53 } 54 55 return c, nil 56 } 57 58 // Process implements proxy.Outbound.Process. 59 func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { 60 outbound := session.OutboundFromContext(ctx) 61 if outbound == nil || !outbound.Target.IsValid() { 62 return newError("target not specified.") 63 } 64 outbound.Name = "socks" 65 inbound := session.InboundFromContext(ctx) 66 if inbound != nil { 67 inbound.SetCanSpliceCopy(2) 68 } 69 // Destination of the inner request. 70 destination := outbound.Target 71 72 // Outbound server. 73 var server *protocol.ServerSpec 74 // Outbound server's destination. 75 var dest net.Destination 76 // Connection to the outbound server. 77 var conn stat.Connection 78 79 if err := retry.ExponentialBackoff(5, 100).On(func() error { 80 server = c.serverPicker.PickServer() 81 dest = server.Destination() 82 rawConn, err := dialer.Dial(ctx, dest) 83 if err != nil { 84 return err 85 } 86 conn = rawConn 87 88 return nil 89 }); err != nil { 90 return newError("failed to find an available destination").Base(err) 91 } 92 93 defer func() { 94 if err := conn.Close(); err != nil { 95 newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) 96 } 97 }() 98 99 p := c.policyManager.ForLevel(0) 100 101 request := &protocol.RequestHeader{ 102 Version: socks5Version, 103 Command: protocol.RequestCommandTCP, 104 Address: destination.Address, 105 Port: destination.Port, 106 } 107 108 switch c.version { 109 case Version_SOCKS4: 110 if request.Address.Family().IsDomain() { 111 ips, err := c.dns.LookupIP(request.Address.Domain(), dns.IPOption{ 112 IPv4Enable: true, 113 }) 114 if err != nil { 115 return err 116 } else if len(ips) == 0 { 117 return dns.ErrEmptyResponse 118 } 119 request.Address = net.IPAddress(ips[0]) 120 } 121 fallthrough 122 case Version_SOCKS4A: 123 request.Version = socks4Version 124 125 if destination.Network == net.Network_UDP { 126 return newError("udp is not supported in socks4") 127 } else if destination.Address.Family().IsIPv6() { 128 return newError("ipv6 is not supported in socks4") 129 } 130 } 131 132 if destination.Network == net.Network_UDP { 133 request.Command = protocol.RequestCommandUDP 134 } 135 136 user := server.PickUser() 137 if user != nil { 138 request.User = user 139 p = c.policyManager.ForLevel(user.Level) 140 } 141 142 if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil { 143 newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx)) 144 } 145 udpRequest, err := ClientHandshake(request, conn, conn) 146 if err != nil { 147 return newError("failed to establish connection to server").AtWarning().Base(err) 148 } 149 if udpRequest != nil { 150 if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 { 151 udpRequest.Address = dest.Address 152 } 153 } 154 155 if err := conn.SetDeadline(time.Time{}); err != nil { 156 newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx)) 157 } 158 159 var newCtx context.Context 160 var newCancel context.CancelFunc 161 if session.TimeoutOnlyFromContext(ctx) { 162 newCtx, newCancel = context.WithCancel(context.Background()) 163 } 164 165 ctx, cancel := context.WithCancel(ctx) 166 timer := signal.CancelAfterInactivity(ctx, func() { 167 cancel() 168 if newCancel != nil { 169 newCancel() 170 } 171 }, p.Timeouts.ConnectionIdle) 172 173 var requestFunc func() error 174 var responseFunc func() error 175 if request.Command == protocol.RequestCommandTCP { 176 requestFunc = func() error { 177 defer timer.SetTimeout(p.Timeouts.DownlinkOnly) 178 return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)) 179 } 180 responseFunc = func() error { 181 defer timer.SetTimeout(p.Timeouts.UplinkOnly) 182 return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)) 183 } 184 } else if request.Command == protocol.RequestCommandUDP { 185 udpConn, err := dialer.Dial(ctx, udpRequest.Destination()) 186 if err != nil { 187 return newError("failed to create UDP connection").Base(err) 188 } 189 defer udpConn.Close() 190 requestFunc = func() error { 191 defer timer.SetTimeout(p.Timeouts.DownlinkOnly) 192 writer := &UDPWriter{Writer: udpConn, Request: request} 193 return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)) 194 } 195 responseFunc = func() error { 196 defer timer.SetTimeout(p.Timeouts.UplinkOnly) 197 reader := &UDPReader{Reader: udpConn} 198 return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)) 199 } 200 } 201 202 if newCtx != nil { 203 ctx = newCtx 204 } 205 206 responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer)) 207 if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { 208 return newError("connection ends").Base(err) 209 } 210 211 return nil 212 } 213 214 func init() { 215 common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 216 return NewClient(ctx, config.(*ClientConfig)) 217 })) 218 }