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