Debian Codegraph @

vendor/clue/socks-react/src/Client.php

raw
1 <?php
2
3 namespace Clue\React\Socks;
4
5 use React\Promise;
6 use React\Promise\PromiseInterface;
7 use React\Promise\Deferred;
8 use React\Socket\ConnectionInterface;
9 use React\Socket\Connector;
10 use React\Socket\ConnectorInterface;
11 use React\Socket\FixedUriConnector;
12 use Exception;
13 use InvalidArgumentException;
14 use RuntimeException;
15
16 final class Client implements ConnectorInterface
17 {
18 /**
19 * @var ConnectorInterface
20 */
21 private $connector;
22
23 private $socksUri;
24
25 private $protocolVersion = 5;
26
27 private $auth = null;
28
29 /**
30 * @param string $socksUri
31 * @param ?ConnectorInterface $connector
32 * @throws InvalidArgumentException
33 */
34 public function __construct(
35 #[\SensitiveParameter]
36 $socksUri,
37 $connector = null
38 ) {
39 if ($connector !== null && !$connector instanceof ConnectorInterface) { // manual type check to support legacy PHP < 7.1
40 throw new InvalidArgumentException('Argument #2 ($connector) expected null|React\Socket\ConnectorInterface');
41 }
42
43 // support `sockss://` scheme for SOCKS over TLS
44 // support `socks+unix://` scheme for Unix domain socket (UDS) paths
45 if (preg_match('/^(socks(?:5|4)?)(s|\+unix):\/\/(.*?@)?(.+?)$/', $socksUri, $match)) {
46 // rewrite URI to parse SOCKS scheme, authentication and dummy host
47 $socksUri = $match[1] . '://' . $match[3] . 'localhost';
48
49 // connector uses appropriate transport scheme and explicit host given
50 $connector = new FixedUriConnector(
51 ($match[2] === 's' ? 'tls://' : 'unix://') . $match[4],
52 $connector ?: new Connector()
53 );
54 }
55
56 // assume default scheme if none is given
57 if (strpos($socksUri, '://') === false) {
58 $socksUri = 'socks://' . $socksUri;
59 }
60
61 // parse URI into individual parts
62 $parts = parse_url($socksUri);
63 if (!$parts || !isset($parts['scheme'], $parts['host'])) {
64 throw new InvalidArgumentException('Invalid SOCKS server URI "' . $socksUri . '"');
65 }
66
67 // assume default port
68 if (!isset($parts['port'])) {
69 $parts['port'] = 1080;
70 }
71
72 // user or password in URI => SOCKS5 authentication
73 if (isset($parts['user']) || isset($parts['pass'])) {
74 if ($parts['scheme'] !== 'socks' && $parts['scheme'] !== 'socks5') {
75 // fail if any other protocol version given explicitly
76 throw new InvalidArgumentException('Authentication requires SOCKS5. Consider using protocol version 5 or waive authentication');
77 }
78 $parts += array('user' => '', 'pass' => '');
79 $this->setAuth(rawurldecode($parts['user']), rawurldecode($parts['pass']));
80 }
81
82 // check for valid protocol version from URI scheme
83 $this->setProtocolVersionFromScheme($parts['scheme']);
84
85 $this->socksUri = $parts['host'] . ':' . $parts['port'];
86 $this->connector = $connector ?: new Connector();
87 }
88
89 private function setProtocolVersionFromScheme($scheme)
90 {
91 if ($scheme === 'socks' || $scheme === 'socks5') {
92 $this->protocolVersion = 5;
93 } elseif ($scheme === 'socks4') {
94 $this->protocolVersion = 4;
95 } else {
96 throw new InvalidArgumentException('Invalid protocol version given "' . $scheme . '://"');
97 }
98 }
99
100 /**
101 * set login data for username/password authentication method (RFC1929)
102 *
103 * @param string $username
104 * @param string $password
105 * @link http://tools.ietf.org/html/rfc1929
106 */
107 private function setAuth(
108 $username,
109 #[\SensitiveParameter]
110 $password
111 ) {
112 if (strlen($username) > 255 || strlen($password) > 255) {
113 throw new InvalidArgumentException('Both username and password MUST NOT exceed a length of 255 bytes each');
114 }
115 $this->auth = pack('C2', 0x01, strlen($username)) . $username . pack('C', strlen($password)) . $password;
116 }
117
118 /**
119 * Establish a TCP/IP connection to the given target URI through the SOCKS server
120 *
121 * Many higher-level networking protocols build on top of TCP. It you're dealing
122 * with one such client implementation, it probably uses/accepts an instance
123 * implementing ReactPHP's `ConnectorInterface` (and usually its default `Connector`
124 * instance). In this case you can also pass this `Connector` instance instead
125 * to make this client implementation SOCKS-aware. That's it.
126 *
127 * @param string $uri
128 * @return PromiseInterface Promise<ConnectionInterface,Exception>
129 */
130 public function connect($uri)
131 {
132 if (strpos($uri, '://') === false) {
133 $uri = 'tcp://' . $uri;
134 }
135
136 $parts = parse_url($uri);
137 if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') {
138 return Promise\reject(new InvalidArgumentException('Invalid target URI specified'));
139 }
140
141 $host = trim($parts['host'], '[]');
142 $port = $parts['port'];
143
144 if (strlen($host) > 255 || $port > 65535 || $port < 0 || (string)$port !== (string)(int)$port) {
145 return Promise\reject(new InvalidArgumentException('Invalid target specified'));
146 }
147
148 // construct URI to SOCKS server to connect to
149 $socksUri = $this->socksUri;
150
151 // append path from URI if given
152 if (isset($parts['path'])) {
153 $socksUri .= $parts['path'];
154 }
155
156 // parse query args
157 $args = array();
158 if (isset($parts['query'])) {
159 parse_str($parts['query'], $args);
160 }
161
162 // append hostname from URI to query string unless explicitly given
163 if (!isset($args['hostname'])) {
164 $args['hostname'] = $host;
165 }
166
167 // append query string
168 $socksUri .= '?' . http_build_query($args, '', '&');
169
170 // append fragment from URI if given
171 if (isset($parts['fragment'])) {
172 $socksUri .= '#' . $parts['fragment'];
173 }
174
175 // start TCP/IP connection to SOCKS server
176 $connecting = $this->connector->connect($socksUri);
177
178 $deferred = new Deferred(function ($_, $reject) use ($uri, $connecting) {
179 $reject(new RuntimeException(
180 'Connection to ' . $uri . ' cancelled while waiting for proxy (ECONNABORTED)',
181 defined('SOCKET_ECONNABORTED') ? SOCKET_ECONNABORTED : 103
182 ));
183
184 // either close active connection or cancel pending connection attempt
185 $connecting->then(function (ConnectionInterface $stream) {
186 $stream->close();
187 }, function () {
188 // ignore to avoid reporting unhandled rejection
189 });
190 $connecting->cancel();
191 });
192
193 // handle SOCKS protocol once connection is ready
194 // resolve plain connection once SOCKS protocol is completed
195 $that = $this;
196 $connecting->then(
197 function (ConnectionInterface $stream) use ($that, $host, $port, $deferred, $uri) {
198 $that->handleConnectedSocks($stream, $host, $port, $deferred, $uri);
199 },
200 function (Exception $e) use ($uri, $deferred) {
201 $deferred->reject($e = new RuntimeException(
202 'Connection to ' . $uri . ' failed because connection to proxy failed (ECONNREFUSED)',
203 defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111,
204 $e
205 ));
206
207 // avoid garbage references by replacing all closures in call stack.
208 // what a lovely piece of code!
209 $r = new \ReflectionProperty('Exception', 'trace');
210 if (PHP_VERSION_ID < 80100) {
211 $r->setAccessible(true);
212 }
213 $trace = $r->getValue($e);
214
215 // Exception trace arguments are not available on some PHP 7.4 installs
216 // @codeCoverageIgnoreStart
217 foreach ($trace as $ti => $one) {
218 if (isset($one['args'])) {
219 foreach ($one['args'] as $ai => $arg) {
220 if ($arg instanceof \Closure) {
221 $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')';
222 }
223 }
224 }
225 }
226 // @codeCoverageIgnoreEnd
227 $r->setValue($e, $trace);
228 }
229 );
230
231 return $deferred->promise();
232 }
233
234 /**
235 * Internal helper used to handle the communication with the SOCKS server
236 *
237 * @param ConnectionInterface $stream
238 * @param string $host
239 * @param int $port
240 * @param Deferred $deferred
241 * @param string $uri
242 * @return void
243 * @internal
244 */
245 public function handleConnectedSocks(ConnectionInterface $stream, $host, $port, Deferred $deferred, $uri)
246 {
247 $reader = new StreamReader();
248 $stream->on('data', array($reader, 'write'));
249
250 $stream->on('error', $onError = function (Exception $e) use ($deferred, $uri) {
251 $deferred->reject(new RuntimeException(
252 'Connection to ' . $uri . ' failed because connection to proxy caused a stream error (EIO)',
253 defined('SOCKET_EIO') ? SOCKET_EIO : 5, $e)
254 );
255 });
256
257 $stream->on('close', $onClose = function () use ($deferred, $uri) {
258 $deferred->reject(new RuntimeException(
259 'Connection to ' . $uri . ' failed because connection to proxy was lost while waiting for response from proxy (ECONNRESET)',
260 defined('SOCKET_ECONNRESET') ? SOCKET_ECONNRESET : 104)
261 );
262 });
263
264 if ($this->protocolVersion === 5) {
265 $promise = $this->handleSocks5($stream, $host, $port, $reader, $uri);
266 } else {
267 $promise = $this->handleSocks4($stream, $host, $port, $reader, $uri);
268 }
269
270 $promise->then(function () use ($deferred, $stream, $reader, $onError, $onClose) {
271 $stream->removeListener('data', array($reader, 'write'));
272 $stream->removeListener('error', $onError);
273 $stream->removeListener('close', $onClose);
274
275 $deferred->resolve($stream);
276 }, function (Exception $error) use ($deferred, $stream, $uri) {
277 // pass custom RuntimeException through as-is, otherwise wrap in protocol error
278 if (!$error instanceof RuntimeException) {
279 $error = new RuntimeException(
280 'Connection to ' . $uri . ' failed because proxy returned invalid response (EBADMSG)',
281 defined('SOCKET_EBADMSG') ? SOCKET_EBADMSG: 71,
282 $error
283 );
284 }
285
286 $deferred->reject($error);
287 $stream->close();
288 });
289 }
290
291 private function handleSocks4(ConnectionInterface $stream, $host, $port, StreamReader $reader, $uri)
292 {
293 // do not resolve hostname. only try to convert to IP
294 $ip = ip2long($host);
295
296 // send IP or (0.0.0.1) if invalid
297 $data = pack('C2nNC', 0x04, 0x01, $port, $ip === false ? 1 : $ip, 0x00);
298
299 if ($ip === false) {
300 // host is not a valid IP => send along hostname (SOCKS4a)
301 $data .= $host . pack('C', 0x00);
302 }
303
304 $stream->write($data);
305
306 return $reader->readBinary(array(
307 'null' => 'C',
308 'status' => 'C',
309 'port' => 'n',
310 'ip' => 'N'
311 ))->then(function ($data) use ($uri) {
312 if ($data['null'] !== 0x00) {
313 throw new Exception('Invalid SOCKS response');
314 }
315 if ($data['status'] !== 0x5a) {
316 throw new RuntimeException(
317 'Connection to ' . $uri . ' failed because proxy refused connection with error code ' . sprintf('0x%02X', $data['status']) . ' (ECONNREFUSED)',
318 defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111
319 );
320 }
321 });
322 }
323
324 private function handleSocks5(ConnectionInterface $stream, $host, $port, StreamReader $reader, $uri)
325 {
326 // protocol version 5
327 $data = pack('C', 0x05);
328
329 $auth = $this->auth;
330 if ($auth === null) {
331 // one method, no authentication
332 $data .= pack('C2', 0x01, 0x00);
333 } else {
334 // two methods, username/password and no authentication
335 $data .= pack('C3', 0x02, 0x02, 0x00);
336 }
337 $stream->write($data);
338
339 $that = $this;
340
341 return $reader->readBinary(array(
342 'version' => 'C',
343 'method' => 'C'
344 ))->then(function ($data) use ($auth, $stream, $reader, $uri) {
345 if ($data['version'] !== 0x05) {
346 throw new Exception('Version/Protocol mismatch');
347 }
348
349 if ($data['method'] === 0x02 && $auth !== null) {
350 // username/password authentication requested and provided
351 $stream->write($auth);
352
353 return $reader->readBinary(array(
354 'version' => 'C',
355 'status' => 'C'
356 ))->then(function ($data) use ($uri) {
357 if ($data['version'] !== 0x01 || $data['status'] !== 0x00) {
358 throw new RuntimeException(
359 'Connection to ' . $uri . ' failed because proxy denied access with given authentication details (EACCES)',
360 defined('SOCKET_EACCES') ? SOCKET_EACCES : 13
361 );
362 }
363 });
364 } else if ($data['method'] !== 0x00) {
365 // any other method than "no authentication"
366 throw new RuntimeException(
367 'Connection to ' . $uri . ' failed because proxy denied access due to unsupported authentication method (EACCES)',
368 defined('SOCKET_EACCES') ? SOCKET_EACCES : 13
369 );
370 }
371 })->then(function () use ($stream, $reader, $host, $port) {
372 // do not resolve hostname. only try to convert to (binary/packed) IP
373 $ip = @inet_pton($host);
374
375 $data = pack('C3', 0x05, 0x01, 0x00);
376 if ($ip === false) {
377 // not an IP, send as hostname
378 $data .= pack('C2', 0x03, strlen($host)) . $host;
379 } else {
380 // send as IPv4 / IPv6
381 $data .= pack('C', (strpos($host, ':') === false) ? 0x01 : 0x04) . $ip;
382 }
383 $data .= pack('n', $port);
384
385 $stream->write($data);
386
387 return $reader->readBinary(array(
388 'version' => 'C',
389 'status' => 'C',
390 'null' => 'C',
391 'type' => 'C'
392 ));
393 })->then(function ($data) use ($reader, $uri) {
394 if ($data['version'] !== 0x05 || $data['null'] !== 0x00) {
395 throw new Exception('Invalid SOCKS response');
396 }
397 if ($data['status'] !== 0x00) {
398 // map limited list of SOCKS error codes to common socket error conditions
399 // @link https://tools.ietf.org/html/rfc1928#section-6
400 if ($data['status'] === Server::ERROR_GENERAL) {
401 throw new RuntimeException(
402 'Connection to ' . $uri . ' failed because proxy refused connection with general server failure (ECONNREFUSED)',
403 defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111
404 );
405 } elseif ($data['status'] === Server::ERROR_NOT_ALLOWED_BY_RULESET) {
406 throw new RuntimeException(
407 'Connection to ' . $uri . ' failed because proxy denied access due to ruleset (EACCES)',
408 defined('SOCKET_EACCES') ? SOCKET_EACCES : 13
409 );
410 } elseif ($data['status'] === Server::ERROR_NETWORK_UNREACHABLE) {
411 throw new RuntimeException(
412 'Connection to ' . $uri . ' failed because proxy reported network unreachable (ENETUNREACH)',
413 defined('SOCKET_ENETUNREACH') ? SOCKET_ENETUNREACH : 101
414 );
415 } elseif ($data['status'] === Server::ERROR_HOST_UNREACHABLE) {
416 throw new RuntimeException(
417 'Connection to ' . $uri . ' failed because proxy reported host unreachable (EHOSTUNREACH)',
418 defined('SOCKET_EHOSTUNREACH') ? SOCKET_EHOSTUNREACH : 113
419 );
420 } elseif ($data['status'] === Server::ERROR_CONNECTION_REFUSED) {
421 throw new RuntimeException(
422 'Connection to ' . $uri . ' failed because proxy reported connection refused (ECONNREFUSED)',
423 defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111
424 );
425 } elseif ($data['status'] === Server::ERROR_TTL) {
426 throw new RuntimeException(
427 'Connection to ' . $uri . ' failed because proxy reported TTL/timeout expired (ETIMEDOUT)',
428 defined('SOCKET_ETIMEDOUT') ? SOCKET_ETIMEDOUT : 110
429 );
430 } elseif ($data['status'] === Server::ERROR_COMMAND_UNSUPPORTED) {
431 throw new RuntimeException(
432 'Connection to ' . $uri . ' failed because proxy does not support the CONNECT command (EPROTO)',
433 defined('SOCKET_EPROTO') ? SOCKET_EPROTO : 71
434 );
435 } elseif ($data['status'] === Server::ERROR_ADDRESS_UNSUPPORTED) {
436 throw new RuntimeException(
437 'Connection to ' . $uri . ' failed because proxy does not support this address type (EPROTO)',
438 defined('SOCKET_EPROTO') ? SOCKET_EPROTO : 71
439 );
440 }
441
442 throw new RuntimeException(
443 'Connection to ' . $uri . ' failed because proxy server refused connection with unknown error code ' . sprintf('0x%02X', $data['status']) . ' (ECONNREFUSED)',
444 defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111
445 );
446 }
447 if ($data['type'] === 0x01) {
448 // IPv4 address => skip IP and port
449 return $reader->readLength(6);
450 } elseif ($data['type'] === 0x03) {
451 // domain name => read domain name length
452 return $reader->readBinary(array(
453 'length' => 'C'
454 ))->then(function ($data) use ($reader) {
455 // skip domain name and port
456 return $reader->readLength($data['length'] + 2);
457 });
458 } elseif ($data['type'] === 0x04) {
459 // IPv6 address => skip IP and port
460 return $reader->readLength(18);
461 } else {
462 throw new Exception('Invalid SOCKS response: Invalid address type');
463 }
464 });
465 }
466 }