Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/NoPrivateNetworkHttpClient.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpClient;
13
14 use Psr\Log\LoggerAwareInterface;
15 use Psr\Log\LoggerInterface;
16 use Symfony\Component\HttpClient\Exception\TransportException;
17 use Symfony\Component\HttpClient\Response\AsyncContext;
18 use Symfony\Component\HttpClient\Response\AsyncResponse;
19 use Symfony\Component\HttpFoundation\IpUtils;
20 use Symfony\Contracts\HttpClient\ChunkInterface;
21 use Symfony\Contracts\HttpClient\HttpClientInterface;
22 use Symfony\Contracts\HttpClient\ResponseInterface;
23 use Symfony\Contracts\Service\ResetInterface;
24
25 /**
26 * Decorator that blocks requests to private networks by default.
27 *
28 * @author Hallison Boaventura <[email protected]>
29 * @author Nicolas Grekas <[email protected]>
30 */
31 final class NoPrivateNetworkHttpClient implements HttpClientInterface, LoggerAwareInterface, ResetInterface
32 {
33 use AsyncDecoratorTrait;
34 use HttpClientTrait;
35
36 private array $defaultOptions = self::OPTIONS_DEFAULTS;
37 private HttpClientInterface $client;
38 private ?array $subnets;
39 private int $ipFlags;
40 private \ArrayObject $dnsCache;
41
42 /**
43 * @param string|array|null $subnets String or array of subnets using CIDR notation that should be considered private.
44 * If null is passed, the standard private subnets will be used.
45 */
46 public function __construct(HttpClientInterface $client, string|array|null $subnets = null)
47 {
48 if (!class_exists(IpUtils::class)) {
49 throw new \LogicException(\sprintf('You cannot use "%s" if the HttpFoundation component is not installed. Try running "composer require symfony/http-foundation".', __CLASS__));
50 }
51
52 if (null === $subnets) {
53 $ipFlags = \FILTER_FLAG_IPV4 | \FILTER_FLAG_IPV6;
54 } else {
55 $ipFlags = 0;
56 foreach ((array) $subnets as $subnet) {
57 $ipFlags |= str_contains($subnet, ':') ? \FILTER_FLAG_IPV6 : \FILTER_FLAG_IPV4;
58 }
59 }
60
61 if (!\defined('STREAM_PF_INET6')) {
62 $ipFlags &= ~\FILTER_FLAG_IPV6;
63 }
64
65 $this->client = $client;
66 $this->subnets = null !== $subnets ? (array) $subnets : null;
67 $this->ipFlags = $ipFlags;
68 $this->dnsCache = new \ArrayObject();
69 }
70
71 public function request(string $method, string $url, array $options = []): ResponseInterface
72 {
73 [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions, true);
74
75 $redirectHeaders = parse_url($url['authority']);
76 $host = $redirectHeaders['host'];
77 $url = implode('', $url);
78 $dnsCache = $this->dnsCache;
79
80 $ip = self::dnsResolve($dnsCache, $host, $this->ipFlags, $options);
81 self::ipCheck($ip, $this->subnets, $this->ipFlags, $host, $url);
82
83 $onProgress = $options['on_progress'] ?? null;
84 $subnets = $this->subnets;
85 $ipFlags = $this->ipFlags;
86
87 $options['on_progress'] = static function (int $dlNow, int $dlSize, array $info) use ($onProgress, $subnets, $ipFlags): void {
88 static $lastPrimaryIp = '';
89
90 if (!\in_array($info['primary_ip'] ?? '', ['', $lastPrimaryIp], true)) {
91 self::ipCheck($info['primary_ip'], $subnets, $ipFlags, null, $info['url']);
92 $lastPrimaryIp = $info['primary_ip'];
93 }
94
95 null !== $onProgress && $onProgress($dlNow, $dlSize, $info);
96 };
97
98 if (0 >= $maxRedirects = $options['max_redirects']) {
99 return new AsyncResponse($this->client, $method, $url, $options);
100 }
101
102 $options['max_redirects'] = 0;
103 $redirectHeaders['with_auth'] = $redirectHeaders['no_auth'] = $options['headers'];
104
105 if (isset($options['normalized_headers']['host']) || isset($options['normalized_headers']['authorization']) || isset($options['normalized_headers']['cookie'])) {
106 $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], static fn ($h) => 0 !== stripos($h, 'Host:') && 0 !== stripos($h, 'Authorization:') && 0 !== stripos($h, 'Cookie:'));
107 }
108
109 return new AsyncResponse($this->client, $method, $url, $options, static function (ChunkInterface $chunk, AsyncContext $context) use (&$method, &$options, $maxRedirects, &$redirectHeaders, $subnets, $ipFlags, $dnsCache): \Generator {
110 if (null !== $chunk->getError() || $chunk->isTimeout() || !$chunk->isFirst()) {
111 yield $chunk;
112
113 return;
114 }
115
116 $statusCode = $context->getStatusCode();
117
118 if ($statusCode < 300 || 400 <= $statusCode || null === $url = $context->getInfo('redirect_url')) {
119 $context->passthru();
120
121 yield $chunk;
122
123 return;
124 }
125
126 $host = parse_url($url, \PHP_URL_HOST);
127 $ip = self::dnsResolve($dnsCache, $host, $ipFlags, $options);
128 self::ipCheck($ip, $subnets, $ipFlags, $host, $url);
129
130 // Do like curl and browsers: turn POST to GET on 301, 302 and 303
131 if (303 === $statusCode || 'POST' === $method && \in_array($statusCode, [301, 302], true)) {
132 $method = 'HEAD' === $method ? 'HEAD' : 'GET';
133 unset($options['body'], $options['json']);
134
135 if (isset($options['normalized_headers']['content-length']) || isset($options['normalized_headers']['content-type']) || isset($options['normalized_headers']['transfer-encoding'])) {
136 $filterContentHeaders = static fn ($h) => 0 !== stripos($h, 'Content-Length:') && 0 !== stripos($h, 'Content-Type:') && 0 !== stripos($h, 'Transfer-Encoding:');
137 $options['headers'] = array_filter($options['headers'], $filterContentHeaders);
138 $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], $filterContentHeaders);
139 $redirectHeaders['with_auth'] = array_filter($redirectHeaders['with_auth'], $filterContentHeaders);
140 }
141 }
142
143 // Authorization and Cookie headers MUST NOT follow except for the initial host name
144 $port = parse_url($url, \PHP_URL_PORT);
145 $options['headers'] = $redirectHeaders['host'] === $host && ($redirectHeaders['port'] ?? null) === $port ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth'];
146
147 static $redirectCount = 0;
148 $context->setInfo('redirect_count', ++$redirectCount);
149
150 $context->replaceRequest($method, $url, $options);
151
152 if ($redirectCount >= $maxRedirects) {
153 $context->passthru();
154 }
155 });
156 }
157
158 /**
159 * @deprecated since Symfony 7.1, configure the logger on the wrapped HTTP client directly instead
160 */
161 public function setLogger(LoggerInterface $logger): void
162 {
163 trigger_deprecation('symfony/http-client', '7.1', 'Configure the logger on the wrapped HTTP client directly instead.');
164
165 if ($this->client instanceof LoggerAwareInterface) {
166 $this->client->setLogger($logger);
167 }
168 }
169
170 public function withOptions(array $options): static
171 {
172 $clone = clone $this;
173 $clone->client = $this->client->withOptions($options);
174 $clone->defaultOptions = self::mergeDefaultOptions($options, $this->defaultOptions);
175
176 return $clone;
177 }
178
179 public function reset(): void
180 {
181 $this->dnsCache->exchangeArray([]);
182
183 if ($this->client instanceof ResetInterface) {
184 $this->client->reset();
185 }
186 }
187
188 private static function dnsResolve(\ArrayObject $dnsCache, string $host, int $ipFlags, array &$options): string
189 {
190 if ($ip = filter_var(trim($host, '[]'), \FILTER_VALIDATE_IP) ?: $options['resolve'][$host] ?? false) {
191 return $ip;
192 }
193
194 if ($dnsCache->offsetExists($host)) {
195 return $dnsCache[$host];
196 }
197
198 if ((\FILTER_FLAG_IPV4 & $ipFlags) && $ip = gethostbynamel($host)) {
199 return $options['resolve'][$host] = $dnsCache[$host] = $ip[0];
200 }
201
202 if (!(\FILTER_FLAG_IPV6 & $ipFlags)) {
203 return $host;
204 }
205
206 if ($ip = dns_get_record($host, \DNS_AAAA)) {
207 $ip = $ip[0]['ipv6'];
208 } elseif (\extension_loaded('sockets')) {
209 if (!$info = socket_addrinfo_lookup($host, 0, ['ai_socktype' => \SOCK_STREAM, 'ai_family' => \AF_INET6])) {
210 return $host;
211 }
212
213 $ip = socket_addrinfo_explain($info[0])['ai_addr']['sin6_addr'];
214 } elseif ('localhost' === $host || 'localhost.' === $host) {
215 $ip = '::1';
216 } else {
217 return $host;
218 }
219
220 return $options['resolve'][$host] = $dnsCache[$host] = $ip;
221 }
222
223 private static function ipCheck(string $ip, ?array $subnets, int $ipFlags, ?string $host, string $url): void
224 {
225 if (null === $subnets) {
226 // Quick check, but not reliable enough, see https://github.com/php/php-src/issues/16944
227 $ipFlags |= \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE;
228 }
229
230 if (false !== filter_var($ip, \FILTER_VALIDATE_IP, $ipFlags) && !IpUtils::checkIp($ip, $subnets ?? IpUtils::PRIVATE_SUBNETS)) {
231 return;
232 }
233
234 if (null !== $host) {
235 $type = 'Host';
236 } else {
237 $host = $ip;
238 $type = 'IP';
239 }
240
241 throw new TransportException($type.\sprintf(' "%s" is blocked for "%s".', $host, $url));
242 }
243 }