Debian Codegraph @

vendor/clue/http-proxy-react/src/ProxyConnector.php

raw
1 <?php
2
3 namespace Clue\React\HttpProxy;
4
5 use Exception;
6 use InvalidArgumentException;
7 use RuntimeException;
8 use React\Promise;
9 use React\Promise\Deferred;
10 use React\Socket\ConnectionInterface;
11 use React\Socket\Connector;
12 use React\Socket\ConnectorInterface;
13 use React\Socket\FixedUriConnector;
14 use React\Socket\UnixConnector;
15
16 /**
17 * A simple Connector that uses an HTTP CONNECT proxy to create plain TCP/IP connections to any destination
18 *
19 * [you] -> [proxy] -> [destination]
20 *
21 * This is most frequently used to issue HTTPS requests to your destination.
22 * However, this is actually performed on a higher protocol layer and this
23 * connector is actually inherently a general-purpose plain TCP/IP connector.
24 *
25 * Note that HTTP CONNECT proxies often restrict which ports one may connect to.
26 * Many (public) proxy servers do in fact limit this to HTTPS (443) only.
27 *
28 * If you want to establish a TLS connection (such as HTTPS) between you and
29 * your destination, you may want to wrap this connector in a SecureConnector
30 * instance.
31 *
32 * Note that communication between the client and the proxy is usually via an
33 * unencrypted, plain TCP/IP HTTP connection. Note that this is the most common
34 * setup, because you can still establish a TLS connection between you and the
35 * destination host as above.
36 *
37 * If you want to connect to a (rather rare) HTTPS proxy, you may want use its
38 * HTTPS port (443) and use a SecureConnector instance to create a secure
39 * connection to the proxy.
40 *
41 * @link https://tools.ietf.org/html/rfc7231#section-4.3.6
42 */
43 class ProxyConnector implements ConnectorInterface
44 {
45 private $connector;
46 private $proxyUri;
47 private $headers = '';
48
49 /**
50 * Instantiate a new ProxyConnector which uses the given $proxyUrl
51 *
52 * @param string $proxyUrl The proxy URL may or may not contain a scheme and
53 * port definition. The default port will be `80` for HTTP (or `443` for
54 * HTTPS), but many common HTTP proxy servers use custom ports.
55 * @param ?ConnectorInterface $connector (Optional) Connector to use.
56 * @param array $httpHeaders Custom HTTP headers to be sent to the proxy.
57 * @throws InvalidArgumentException if the proxy URL is invalid
58 */
59 public function __construct(
60 #[\SensitiveParameter]
61 $proxyUrl,
62 $connector = null,
63 array $httpHeaders = array()
64 ) {
65 // support `http+unix://` scheme for Unix domain socket (UDS) paths
66 if (preg_match('/^http\+unix:\/\/(.*?@)?(.+?)$/', $proxyUrl, $match)) {
67 // rewrite URI to parse authentication from dummy host
68 $proxyUrl = 'http://' . $match[1] . 'localhost';
69
70 // connector uses Unix transport scheme and explicit path given
71 $connector = new FixedUriConnector(
72 'unix://' . $match[2],
73 $connector ?: new UnixConnector() // @codeCoverageIgnore
74 );
75 }
76
77 if (strpos($proxyUrl, '://') === false) {
78 $proxyUrl = 'http://' . $proxyUrl;
79 }
80
81 $parts = parse_url($proxyUrl);
82 if (!$parts || !isset($parts['scheme'], $parts['host']) || ($parts['scheme'] !== 'http' && $parts['scheme'] !== 'https')) {
83 throw new InvalidArgumentException('Invalid proxy URL "' . $proxyUrl . '"');
84 }
85
86 if ($connector !== null && !$connector instanceof ConnectorInterface) { // manual type check to support legacy PHP < 7.1
87 throw new \InvalidArgumentException('Argument #2 ($connector) expected null|React\Socket\ConnectorInterface');
88 }
89
90 // apply default port and TCP/TLS transport for given scheme
91 if (!isset($parts['port'])) {
92 $parts['port'] = $parts['scheme'] === 'https' ? 443 : 80;
93 }
94 $parts['scheme'] = $parts['scheme'] === 'https' ? 'tls' : 'tcp';
95
96 $this->connector = $connector ?: new Connector();
97 $this->proxyUri = $parts['scheme'] . '://' . $parts['host'] . ':' . $parts['port'];
98
99 // prepare Proxy-Authorization header if URI contains username/password
100 if (isset($parts['user']) || isset($parts['pass'])) {
101 $this->headers = 'Proxy-Authorization: Basic ' . base64_encode(
102 rawurldecode($parts['user'] . ':' . (isset($parts['pass']) ? $parts['pass'] : ''))
103 ) . "\r\n";
104 }
105
106 // append any additional custom request headers
107 foreach ($httpHeaders as $name => $values) {
108 foreach ((array)$values as $value) {
109 $this->headers .= $name . ': ' . $value . "\r\n";
110 }
111 }
112 }
113
114 public function connect($uri)
115 {
116 if (strpos($uri, '://') === false) {
117 $uri = 'tcp://' . $uri;
118 }
119
120 $parts = parse_url($uri);
121 if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') {
122 return Promise\reject(new InvalidArgumentException('Invalid target URI specified'));
123 }
124
125 $target = $parts['host'] . ':' . $parts['port'];
126
127 // construct URI to HTTP CONNECT proxy server to connect to
128 $proxyUri = $this->proxyUri;
129
130 // append path from URI if given
131 if (isset($parts['path'])) {
132 $proxyUri .= $parts['path'];
133 }
134
135 // parse query args
136 $args = array();
137 if (isset($parts['query'])) {
138 parse_str($parts['query'], $args);
139 }
140
141 // append hostname from URI to query string unless explicitly given
142 if (!isset($args['hostname'])) {
143 $args['hostname'] = trim($parts['host'], '[]');
144 }
145
146 // append query string
147 $proxyUri .= '?' . http_build_query($args, '', '&');
148
149 // append fragment from URI if given
150 if (isset($parts['fragment'])) {
151 $proxyUri .= '#' . $parts['fragment'];
152 }
153
154 $connecting = $this->connector->connect($proxyUri);
155
156 $deferred = new Deferred(function ($_, $reject) use ($connecting, $uri) {
157 $reject(new RuntimeException(
158 'Connection to ' . $uri . ' cancelled while waiting for proxy (ECONNABORTED)',
159 defined('SOCKET_ECONNABORTED') ? SOCKET_ECONNABORTED : 103
160 ));
161
162 // either close active connection or cancel pending connection attempt
163 $connecting->then(function (ConnectionInterface $stream) {
164 $stream->close();
165 }, function () {
166 // ignore to avoid reporting unhandled rejection
167 });
168 $connecting->cancel();
169 });
170
171 $headers = $this->headers;
172 $connecting->then(function (ConnectionInterface $stream) use ($target, $headers, $deferred, $uri) {
173 // keep buffering data until headers are complete
174 $buffer = '';
175 $stream->on('data', $fn = function ($chunk) use (&$buffer, $deferred, $stream, &$fn, $uri) {
176 $buffer .= $chunk;
177
178 $pos = strpos($buffer, "\r\n\r\n");
179 if ($pos !== false) {
180 // end of headers received => stop buffering
181 $stream->removeListener('data', $fn);
182 $fn = null;
183
184 // try to parse headers as response message
185 if (!preg_match('/^HTTP\/1\.[01] ([0-9]{3})( .*)?\r\n/', $buffer, $matches)) {
186 $deferred->reject(new RuntimeException(
187 'Connection to ' . $uri . ' failed because proxy returned invalid response (EBADMSG)',
188 defined('SOCKET_EBADMSG') ? SOCKET_EBADMSG : 71
189 ));
190 $stream->close();
191 return;
192 }
193
194 $statusCode = (int) $matches[1];
195 $reasonPhrase = isset($matches[2]) ? trim($matches[2]) : '';
196
197 if ($statusCode === 407) {
198 // map status code 407 (Proxy Authentication Required) to EACCES
199 $deferred->reject(new RuntimeException(
200 'Connection to ' . $uri . ' failed because proxy denied access with HTTP error code ' . $statusCode . ' (' . $reasonPhrase . ') (EACCES)',
201 defined('SOCKET_EACCES') ? SOCKET_EACCES : 13
202 ));
203 $stream->close();
204 return;
205 } elseif ($statusCode < 200 || $statusCode >= 300) {
206 // map non-2xx status code to ECONNREFUSED
207 $deferred->reject(new RuntimeException(
208 'Connection to ' . $uri . ' failed because proxy refused connection with HTTP error code ' . $statusCode . ' (' . $reasonPhrase . ') (ECONNREFUSED)',
209 defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111
210 ));
211 $stream->close();
212 return;
213 }
214
215 // all okay, resolve with stream instance
216 $deferred->resolve($stream);
217
218 // emit remaining incoming as data event
219 $buffer = (string)substr($buffer, $pos + 4);
220 if ($buffer !== '') {
221 $stream->emit('data', array($buffer));
222 $buffer = '';
223 }
224 return;
225 }
226
227 // stop buffering when 8 KiB have been read
228 if (isset($buffer[8192])) {
229 $deferred->reject(new RuntimeException(
230 'Connection to ' . $uri . ' failed because proxy response headers exceed maximum of 8 KiB (EMSGSIZE)',
231 defined('SOCKET_EMSGSIZE') ? SOCKET_EMSGSIZE : 90
232 ));
233 $stream->close();
234 }
235 });
236
237 $stream->on('error', function (Exception $e) use ($deferred, $uri) {
238 $deferred->reject(new RuntimeException(
239 'Connection to ' . $uri . ' failed because connection to proxy caused a stream error (EIO)',
240 defined('SOCKET_EIO') ? SOCKET_EIO : 5,
241 $e
242 ));
243 });
244
245 $stream->on('close', function () use ($deferred, $uri) {
246 $deferred->reject(new RuntimeException(
247 'Connection to ' . $uri . ' failed because connection to proxy was lost while waiting for response (ECONNRESET)',
248 defined('SOCKET_ECONNRESET') ? SOCKET_ECONNRESET : 104
249 ));
250 });
251
252 $stream->write("CONNECT " . $target . " HTTP/1.1\r\nHost: " . $target . "\r\n" . $headers . "\r\n");
253 }, function (Exception $e) use ($deferred, $uri) {
254 $deferred->reject($e = new RuntimeException(
255 'Connection to ' . $uri . ' failed because connection to proxy failed (ECONNREFUSED)',
256 defined('SOCKET_ECONNREFUSED') ? SOCKET_ECONNREFUSED : 111,
257 $e
258 ));
259
260 // avoid garbage references by replacing all closures in call stack.
261 // what a lovely piece of code!
262 $r = new \ReflectionProperty('Exception', 'trace');
263 if (PHP_VERSION_ID < 80100) {
264 $r->setAccessible(true); // @codeCoverageIgnore
265 }
266 $trace = $r->getValue($e);
267
268 // Exception trace arguments are not available on some PHP 7.4 installs
269 // @codeCoverageIgnoreStart
270 foreach ($trace as $ti => $one) {
271 if (isset($one['args'])) {
272 foreach ($one['args'] as $ai => $arg) {
273 if ($arg instanceof \Closure) {
274 $trace[$ti]['args'][$ai] = 'Object(' . get_class($arg) . ')';
275 }
276 }
277 }
278 }
279 // @codeCoverageIgnoreEnd
280 $r->setValue($e, $trace);
281 });
282
283 return $deferred->promise();
284 }
285 }