github.com/xraypb/xray-core@v1.6.6/proxy/socks/client.go (about) 1 package socks 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/dns" 17 "github.com/xraypb/xray-core/features/policy" 18 "github.com/xraypb/xray-core/transport" 19 "github.com/xraypb/xray-core/transport/internet" 20 "github.com/xraypb/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 // Destination of the inner request. 65 destination := outbound.Target 66 67 // Outbound server. 68 var server *protocol.ServerSpec 69 // Outbound server's destination. 70 var dest net.Destination 71 // Connection to the outbound server. 72 var conn stat.Connection 73 74 if err := retry.ExponentialBackoff(5, 100).On(func() error { 75 server = c.serverPicker.PickServer() 76 dest = server.Destination() 77 rawConn, err := dialer.Dial(ctx, dest) 78 if err != nil { 79 return err 80 } 81 conn = rawConn 82 83 return nil 84 }); err != nil { 85 return newError("failed to find an available destination").Base(err) 86 } 87 88 defer func() { 89 if err := conn.Close(); err != nil { 90 newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) 91 } 92 }() 93 94 p := c.policyManager.ForLevel(0) 95 96 request := &protocol.RequestHeader{ 97 Version: socks5Version, 98 Command: protocol.RequestCommandTCP, 99 Address: destination.Address, 100 Port: destination.Port, 101 } 102 103 switch c.version { 104 case Version_SOCKS4: 105 if request.Address.Family().IsDomain() { 106 ips, err := c.dns.LookupIP(request.Address.Domain(), dns.IPOption{ 107 IPv4Enable: true, 108 }) 109 if err != nil { 110 return err 111 } else if len(ips) == 0 { 112 return dns.ErrEmptyResponse 113 } 114 request.Address = net.IPAddress(ips[0]) 115 } 116 fallthrough 117 case Version_SOCKS4A: 118 request.Version = socks4Version 119 120 if destination.Network == net.Network_UDP { 121 return newError("udp is not supported in socks4") 122 } else if destination.Address.Family().IsIPv6() { 123 return newError("ipv6 is not supported in socks4") 124 } 125 } 126 127 if destination.Network == net.Network_UDP { 128 request.Command = protocol.RequestCommandUDP 129 } 130 131 user := server.PickUser() 132 if user != nil { 133 request.User = user 134 p = c.policyManager.ForLevel(user.Level) 135 } 136 137 if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil { 138 newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx)) 139 } 140 udpRequest, err := ClientHandshake(request, conn, conn) 141 if err != nil { 142 return newError("failed to establish connection to server").AtWarning().Base(err) 143 } 144 if udpRequest != nil { 145 if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 { 146 udpRequest.Address = dest.Address 147 } 148 } 149 150 if err := conn.SetDeadline(time.Time{}); err != nil { 151 newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx)) 152 } 153 154 ctx, cancel := context.WithCancel(ctx) 155 timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle) 156 157 var requestFunc func() error 158 var responseFunc func() error 159 if request.Command == protocol.RequestCommandTCP { 160 requestFunc = func() error { 161 defer timer.SetTimeout(p.Timeouts.DownlinkOnly) 162 return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)) 163 } 164 responseFunc = func() error { 165 defer timer.SetTimeout(p.Timeouts.UplinkOnly) 166 return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)) 167 } 168 } else if request.Command == protocol.RequestCommandUDP { 169 udpConn, err := dialer.Dial(ctx, udpRequest.Destination()) 170 if err != nil { 171 return newError("failed to create UDP connection").Base(err) 172 } 173 defer udpConn.Close() 174 requestFunc = func() error { 175 defer timer.SetTimeout(p.Timeouts.DownlinkOnly) 176 writer := &UDPWriter{Writer: udpConn, Request: request} 177 return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)) 178 } 179 responseFunc = func() error { 180 defer timer.SetTimeout(p.Timeouts.UplinkOnly) 181 reader := &UDPReader{Reader: udpConn} 182 return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)) 183 } 184 } 185 186 responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer)) 187 if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { 188 return newError("connection ends").Base(err) 189 } 190 191 return nil 192 } 193 194 func init() { 195 common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 196 return NewClient(ctx, config.(*ClientConfig)) 197 })) 198 }