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