PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.5
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.5
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / vendor_prefixed / guzzlehttp / guzzle / src / Handler / CurlFactory.php

CurlFactory.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.5, at vendor_prefixed/guzzlehttp/guzzle/src/Handler/CurlFactory.php

1,980 lines 102.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace YoastSEO_Vendor\GuzzleHttp\Handler;
4
5 use YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException;
6 use YoastSEO_Vendor\GuzzleHttp\Exception\RequestException;
7 use YoastSEO_Vendor\GuzzleHttp\Multiplexing;
8 use YoastSEO_Vendor\GuzzleHttp\Promise as P;
9 use YoastSEO_Vendor\GuzzleHttp\Promise\FulfilledPromise;
10 use YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface;
11 use YoastSEO_Vendor\GuzzleHttp\Psr7;
12 use YoastSEO_Vendor\GuzzleHttp\Psr7\LazyOpenStream;
13 use YoastSEO_Vendor\GuzzleHttp\Psr7\Uri;
14 use YoastSEO_Vendor\GuzzleHttp\TransferStats;
15 use YoastSEO_Vendor\GuzzleHttp\TransportSharing;
16 use YoastSEO_Vendor\GuzzleHttp\Utils;
17 use YoastSEO_Vendor\Psr\Http\Message\RequestInterface;
18 use YoastSEO_Vendor\Psr\Http\Message\UriInterface;
19 /**
20 * Creates curl resources from a request
21 *
22 * @final
23 */
24 class CurlFactory implements \YoastSEO_Vendor\GuzzleHttp\Handler\CurlFactoryInterface
25 {
26 public const CURL_VERSION_STR = 'curl_version';
27 private const DELEGATED_PROXY_TUNNEL_OWNER = 'proxy-tunnel:delegated-to-libcurl';
28 /**
29 * String-valued proxy credential cURL options whose values feed the
30 * connection-reuse section signatures. Stringable values are cast
31 * exactly once, before signature computation, so the signature and
32 * ext-curl observe the same string; a stateful __toString() could
33 * otherwise produce one value for the signature and a different one on
34 * the wire, giving two credentials the same section. Numeric options
35 * (CURLOPT_PROXYTYPE, CURLOPT_PROXY_SSLVERSION) and blob options
36 * (CURLOPT_PROXY_SSLCERT_BLOB) are deliberately excluded.
37 */
38 private const STRINGABLE_PROXY_CREDENTIAL_OPTIONS = ['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD', 'CURLOPT_PROXY_SSLCERT', 'CURLOPT_PROXY_SSLKEY', 'CURLOPT_PROXY_KEYPASSWD', 'CURLOPT_PROXY_TLSAUTH_USERNAME', 'CURLOPT_PROXY_TLSAUTH_PASSWORD'];
39 /**
40 * @deprecated
41 */
42 public const LOW_CURL_VERSION_NUMBER = '7.21.2';
43 /**
44 * @var resource[]|\CurlHandle[]
45 */
46 private $handles = [];
47 /**
48 * @var string|null Owner signature of the proxy tunnels that pooled idle
49 * handles may still hold
50 */
51 private $proxyTunnelOwner;
52 /**
53 * @var bool Whether an in-domain handle has been pooled since the last purge
54 */
55 private $poolMayHoldTunnels = \false;
56 /**
57 * @var int Total number of idle handles to keep in cache
58 */
59 private $maxHandles;
60 /**
61 * @var resource|\CurlShareHandle|null
62 */
63 private $shareHandle;
64 /**
65 * @var string
66 */
67 private $shareMode;
68 /**
69 * @var bool Whether the configured share handle may own a connection
70 * cache populated outside this factory
71 */
72 private $opaqueShareConnectionCache = \false;
73 /**
74 * @param int $maxHandles Maximum number of idle handles.
75 * @param resource|\CurlShareHandle|CurlShareHandleState|null $shareHandle
76 */
77 public function __construct(int $maxHandles, string $shareMode = \YoastSEO_Vendor\GuzzleHttp\TransportSharing::NONE, $shareHandle = null)
78 {
79 $this->maxHandles = $maxHandles;
80 $this->shareMode = \YoastSEO_Vendor\GuzzleHttp\Handler\CurlShareHandleState::normalizeMode($shareMode, 'transport_sharing');
81 if ($shareHandle instanceof \YoastSEO_Vendor\GuzzleHttp\Handler\CurlShareHandleState) {
82 if ($shareHandle->mode !== $this->shareMode) {
83 throw new \InvalidArgumentException('The cURL share handle state mode does not match the configured transport sharing mode.');
84 }
85 // A Guzzle-created handler-lifetime state locks only DNS and TLS
86 // session data, so its handle can never own a connection cache.
87 $shareHandle = $shareHandle->handle;
88 } elseif ($shareHandle !== null) {
89 // An externally supplied handle's lock set and cached contents
90 // cannot be inspected from PHP, so it may own a connection cache
91 // populated outside this factory.
92 $this->opaqueShareConnectionCache = \true;
93 }
94 if ($this->shareMode === \YoastSEO_Vendor\GuzzleHttp\TransportSharing::NONE && $shareHandle !== null) {
95 throw new \InvalidArgumentException('A cURL share handle cannot be provided when transport sharing is disabled.');
96 }
97 if ($this->shareMode !== \YoastSEO_Vendor\GuzzleHttp\TransportSharing::NONE && $shareHandle === null) {
98 throw new \InvalidArgumentException('A cURL share handle is required when transport sharing is enabled.');
99 }
100 if ($shareHandle !== null && !self::isCurlShareHandle($shareHandle)) {
101 throw new \InvalidArgumentException('A cURL share handle must be an instance of CurlShareHandle or a curl_share resource.');
102 }
103 $this->shareHandle = $shareHandle;
104 }
105 /**
106 * @param mixed $value
107 */
108 private static function isCurlShareHandle($value) : bool
109 {
110 if (\PHP_VERSION_ID < 80000) {
111 return \is_resource($value) && \get_resource_type($value) === 'curl_share';
112 }
113 return $value instanceof \CurlShareHandle;
114 }
115 public function create(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $options) : \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle
116 {
117 self::validateRequestUriScheme($request);
118 if (isset($options['on_trailers']) && !\is_callable($options['on_trailers'])) {
119 throw new \InvalidArgumentException('on_trailers must be callable');
120 }
121 $protocolVersion = $request->getProtocolVersion();
122 if ('' === $protocolVersion) {
123 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Sending a request with an empty protocol version is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
124 $protocolVersion = '1.1';
125 $request = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
126 }
127 $multiplex = self::normalizeMultiplex($options);
128 $requiredMultiplex = \in_array($multiplex, [\YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_EAGER, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_WAIT], \true);
129 if ($requiredMultiplex && isset($options['curl']) && \is_array($options['curl'])) {
130 $requiredModeConflicts = [\CURLOPT_HTTP_VERSION => ['CURLOPT_HTTP_VERSION', 'the request protocol version'], \CURLOPT_URL => ['CURLOPT_URL', 'the request URI'], \CURLOPT_FOLLOWLOCATION => ['CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option']];
131 foreach ($requiredModeConflicts as $option => [$name, $replacement]) {
132 if (\array_key_exists($option, $options['curl'])) {
133 // Key presence alone conflicts: whatever the raw value,
134 // it is a second authority over the protocol or route,
135 // applied after the required mode's decisions.
136 throw new \InvalidArgumentException(\sprintf('The "multiplex" request option cannot be required when the raw %s cURL option is set; remove the raw option and use %s instead.', $name, $replacement));
137 }
138 }
139 }
140 if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
141 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsHttp2()) {
142 if ($requiredMultiplex) {
143 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException('Required multiplexing needs libcurl 8.14.0 or newer built with HTTP/2 support.', $request);
144 }
145 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException('HTTP/2 is supported by the cURL handler, however libcurl is built without HTTP/2 support.', $request);
146 }
147 } elseif ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
148 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException(\sprintf('HTTP/%s is not supported by the cURL handler.', $protocolVersion), $request);
149 }
150 if (isset($options['curl']['body_as_string'])) {
151 $options['_body_as_string'] = $options['curl']['body_as_string'];
152 unset($options['curl']['body_as_string']);
153 }
154 self::triggerUnsupportedRequestOptionDeprecations($options);
155 self::triggerUnsupportedCurlOptionDeprecations($options);
156 self::triggerConflictingCurlOptionDeprecations($options);
157 // Capture the managed Proxy-Authorization values before header
158 // serialization so they never enter the origin header list, and
159 // record whether a deprecated raw CURLOPT_HTTPHEADER value replaces
160 // every generated header, the managed values included. Key presence
161 // alone replaces: an empty or null raw value still suppresses the
162 // generated list.
163 $managedProxyAuthorization = self::managedProxyAuthorizationHeaderLines($request);
164 $rawHttpHeadersReplaceManaged = isset($options['curl']) && \is_array($options['curl']) && \array_key_exists(\CURLOPT_HTTPHEADER, $options['curl']);
165 $easy = new \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle();
166 $easy->request = $request;
167 $easy->options = $options;
168 $conf = $this->getDefaultConf($easy);
169 $this->applyMethod($easy, $conf);
170 $this->applyHandlerOptions($easy, $conf);
171 $this->applyHeaders($easy, $conf);
172 unset($conf['_headers']);
173 // Add handler options from the request configuration options
174 if (isset($options['curl'])) {
175 $conf = \array_replace($conf, $options['curl']);
176 }
177 self::assertFinalProxyOptionTypes($conf, $requiredMultiplex && 'https' !== $request->getUri()->getScheme());
178 self::isolatePreProxyOnAffectedCurl($conf);
179 self::normalizeStringableProxyCredentialOptions($conf);
180 if ($requiredMultiplex) {
181 self::assertRequiredMultiplexRouteDirect($easy, $conf);
182 self::assertRequiredMultiplexAuthSupported($conf);
183 }
184 self::normalizeCurlHeaderOptions($conf);
185 self::applyProxyAuthorizationHeaderHandling($request, $conf);
186 self::applyManagedProxyAuthorization($request, $conf, $managedProxyAuthorization, $rawHttpHeadersReplaceManaged);
187 // Validate the appended managed lines too: a custom RequestInterface
188 // can bypass a normal PSR-7 implementation's header validation.
189 self::normalizeCurlHeaderOptions($conf);
190 $this->rejectRequestLevelShareConflict($options);
191 self::rejectRequestLevelShareWithProxyAuth($request, $options, $conf);
192 if ($this->shareHandle !== null) {
193 // Conservative blanket mode: a configured share handle hides the
194 // pooled connections' provenance, so sectioned reuse cannot reason
195 // about them.
196 self::forceFreshConnectionForAuthenticatedProxy($request, $conf);
197 $this->isolateOpaqueShareAnonymousProxyTunnel($request, $conf);
198 } else {
199 $signature = self::proxyTunnelSignature($request, $conf);
200 $easy->proxyTunnelSignature = $signature;
201 if ($signature !== null && $signature !== $this->proxyTunnelOwner) {
202 if ($this->poolMayHoldTunnels) {
203 // Pooled idle handles may hold a different owner's tunnel.
204 $this->discardIdleHandles();
205 $this->poolMayHoldTunnels = \false;
206 }
207 // The first in-domain owner latches without purging: the pool
208 // provably holds no in-domain tunnel yet.
209 $this->proxyTunnelOwner = $signature;
210 }
211 }
212 $easy->effectiveProxy = self::getEffectiveProxy($conf);
213 $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
214 if ($this->shareHandle !== null) {
215 if (!\defined('CURLOPT_SHARE')) {
216 throw new \InvalidArgumentException('The configured cURL share handle requires CURLOPT_SHARE, but it is not available in the installed PHP cURL extension.');
217 }
218 $conf[(int) \constant('CURLOPT_SHARE')] = $this->shareHandle;
219 }
220 if (\defined('CURLOPT_PIPEWAIT')) {
221 $easy->usesPipewait = !empty($conf[(int) \constant('CURLOPT_PIPEWAIT')]);
222 }
223 $handle = $this->handles ? \array_pop($this->handles) : \curl_init();
224 if (\false === $handle) {
225 throw new \RuntimeException('Can not initialize cURL handle.');
226 }
227 $easy->handle = $handle;
228 try {
229 $this->applyCurlOptions($handle, $conf);
230 } catch (\Throwable $e) {
231 if (\PHP_VERSION_ID < 80000 && \is_resource($handle)) {
232 \curl_close($handle);
233 }
234 unset($easy->handle);
235 throw $e;
236 }
237 return $easy;
238 }
239 /**
240 * @param resource|\CurlHandle $handle
241 * @param array<int|string, mixed> $conf
242 */
243 private function applyCurlOptions($handle, array $conf) : void
244 {
245 foreach ($conf as $option => $value) {
246 if (!\is_int($option)) {
247 throw new \InvalidArgumentException(\sprintf('Invalid cURL option %s.', self::formatCurlOption($option)));
248 }
249 try {
250 $success = \curl_setopt($handle, $option, $value);
251 } catch (\Throwable $e) {
252 throw new \InvalidArgumentException(\sprintf('Unable to set cURL option %s: %s', self::formatCurlOption($option), $e->getMessage()), 0, $e);
253 }
254 if (!$success) {
255 throw new \InvalidArgumentException(\sprintf('Unable to set cURL option %s.', self::formatCurlOption($option)));
256 }
257 }
258 }
259 /**
260 * @param array<int|string, mixed> $conf
261 */
262 private static function normalizeStringableProxyCredentialOptions(array &$conf) : void
263 {
264 foreach (self::STRINGABLE_PROXY_CREDENTIAL_OPTIONS as $name) {
265 if (!\defined($name)) {
266 continue;
267 }
268 $option = (int) \constant($name);
269 if (!isset($conf[$option]) || !\is_object($conf[$option]) || !\method_exists($conf[$option], '__toString')) {
270 continue;
271 }
272 try {
273 $conf[$option] = (string) $conf[$option];
274 } catch (\Throwable $e) {
275 // Wrap the failure exactly as applyCurlOptions() does for a
276 // value that cannot be applied.
277 throw new \InvalidArgumentException(\sprintf('Unable to set cURL option %s: %s', self::formatCurlOption($option), $e->getMessage()), 0, $e);
278 }
279 }
280 }
281 private function rejectRequestLevelShareConflict(array $options) : void
282 {
283 if ($this->shareHandle === null) {
284 return;
285 }
286 if (!\defined('CURLOPT_SHARE') || !isset($options['curl']) || !\is_array($options['curl']) || !\array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl'])) {
287 return;
288 }
289 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with configured transport sharing.');
290 }
291 private static function normalizeMultiplex(array $options) : ?string
292 {
293 $multiplex = $options['multiplex'] ?? null;
294 if ($multiplex === null) {
295 // Absent/null leaves multiplexing to libcurl: no CURLOPT_PIPEWAIT
296 // is written and no guarantees apply.
297 return null;
298 }
299 if (!\in_array($multiplex, [\YoastSEO_Vendor\GuzzleHttp\Multiplexing::NONE, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::EAGER, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::WAIT, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_EAGER, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_WAIT], \true)) {
300 throw new \InvalidArgumentException(\sprintf('The "multiplex" option must be null or a GuzzleHttp\\Multiplexing::* constant; received %s.', \get_debug_type($multiplex)));
301 }
302 return $multiplex;
303 }
304 private static function assertRequiredMultiplexSupported(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : void
305 {
306 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsRequiredMultiplex()) {
307 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException('Required multiplexing needs libcurl 8.14.0 or newer built with HTTP/2 support.', $easy->request);
308 }
309 }
310 /**
311 * Required multiplexing sends cleartext requests with HTTP/2 prior
312 * knowledge, which an HTTP proxy hop silently downgrades, so the request
313 * must reach the origin directly. The check runs against the final
314 * merged cURL configuration because deprecated raw proxy options are
315 * applied after Guzzle's own decisions and may add, replace, or disable
316 * the selected proxy. Value types that ext-curl would coerce are
317 * rejected as ambiguous, and only the exact CURLOPT_NOPROXY wildcard '*'
318 * counts as disabling the primary proxy and pre-proxy: host-specific
319 * patterns are conservatively treated as leaving them active.
320 *
321 * @param array<int|string, mixed> $conf
322 */
323 private static function assertRequiredMultiplexRouteDirect(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array $conf) : void
324 {
325 if ('https' === $easy->request->getUri()->getScheme()) {
326 return;
327 }
328 $proxyOptions = [\CURLOPT_PROXY => 'CURLOPT_PROXY'];
329 if (\defined('CURLOPT_NOPROXY')) {
330 $proxyOptions[(int) \constant('CURLOPT_NOPROXY')] = 'CURLOPT_NOPROXY';
331 }
332 if (\defined('CURLOPT_PRE_PROXY')) {
333 $proxyOptions[(int) \constant('CURLOPT_PRE_PROXY')] = 'CURLOPT_PRE_PROXY';
334 }
335 foreach ($proxyOptions as $option => $name) {
336 if (\array_key_exists($option, $conf) && !\is_string($conf[$option])) {
337 throw new \InvalidArgumentException(\sprintf('The "multiplex" request option cannot be required when the final %s cURL option value is not a string.', $name));
338 }
339 }
340 if (\defined('CURLOPT_NOPROXY') && ($conf[(int) \constant('CURLOPT_NOPROXY')] ?? null) === '*') {
341 // libcurl's exact wildcard disables the primary proxy and the
342 // pre-proxy together, leaving a direct route.
343 return;
344 }
345 if (self::getEffectiveProxy($conf) !== null || \defined('CURLOPT_PRE_PROXY') && ($conf[(int) \constant('CURLOPT_PRE_PROXY')] ?? '') !== '') {
346 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException('Required multiplexing cannot be guaranteed for cleartext requests sent through a proxy.', $easy->request);
347 }
348 }
349 /**
350 * libcurl forces NTLM-authenticated transfers onto HTTP/1.1: when the
351 * server picks NTLM from the offered mask, the connection is closed and
352 * the request is retried over HTTP/1.1 whatever HTTP version was asked
353 * for, silently defeating the required protocol guarantee on both
354 * cleartext and TLS routes. The final merged mask is checked so the
355 * deprecated "auth" request option and the raw CURLOPT_HTTPAUTH cURL
356 * option are both covered, and any mask permitting NTLM, such as
357 * CURLAUTH_ANY, is rejected because the selection is server-controlled.
358 *
359 * @param array<int|string, mixed> $conf
360 */
361 private static function assertRequiredMultiplexAuthSupported(array $conf) : void
362 {
363 if (!\array_key_exists(\CURLOPT_HTTPAUTH, $conf)) {
364 return;
365 }
366 $auth = $conf[\CURLOPT_HTTPAUTH];
367 if (!\is_scalar($auth)) {
368 throw new \InvalidArgumentException('The "multiplex" request option cannot be required when the final CURLOPT_HTTPAUTH cURL option value is not an integer.');
369 }
370 $ntlmBits = \CURLAUTH_NTLM;
371 if (\defined('CURLAUTH_NTLM_WB')) {
372 $ntlmBits |= (int) \constant('CURLAUTH_NTLM_WB');
373 }
374 if (((int) $auth & $ntlmBits) !== 0) {
375 throw new \InvalidArgumentException('The "multiplex" request option cannot be required when the final CURLOPT_HTTPAUTH cURL option value permits NTLM; libcurl retries NTLM authentication over HTTP/1.1.');
376 }
377 }
378 /**
379 * @param mixed $proxyConf
380 */
381 private static function assertResolvedProxySupported(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, $proxyConf) : void
382 {
383 if (!\is_string($proxyConf) || $proxyConf === '') {
384 return;
385 }
386 $scheme = self::proxyScheme($proxyConf);
387 if ($scheme !== null && \preg_match('/^[a-z][a-z0-9.+-]*$/D', $scheme) !== 1) {
388 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('The proxy URL is malformed.', $request);
389 }
390 if ($scheme === 'https' && !\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsHttpsProxy()) {
391 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('HTTPS proxies are not supported by the installed libcurl; libcurl 7.52.0 or newer built with HTTPS-proxy support is required.', $request);
392 }
393 }
394 /**
395 * @return array{0: mixed, 1: string}
396 */
397 private static function resolveProxy(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $options) : array
398 {
399 $proxyConf = null;
400 $noProxyConf = '';
401 if (isset($options['proxy'])) {
402 if (!\is_array($options['proxy'])) {
403 $proxyConf = $options['proxy'];
404 } else {
405 $scheme = $request->getUri()->getScheme();
406 if (isset($options['proxy'][$scheme])) {
407 if (isset($options['proxy']['no']) && \YoastSEO_Vendor\GuzzleHttp\Utils::isUriInNoProxy($request->getUri(), $options['proxy']['no'])) {
408 $proxyConf = '';
409 $noProxyConf = '*';
410 } else {
411 $proxyConf = $options['proxy'][$scheme];
412 }
413 }
414 }
415 }
416 if ($proxyConf === null) {
417 $proxyConf = \YoastSEO_Vendor\GuzzleHttp\Handler\ProxyEnvironment::getProxyForScheme($request->getUri()->getScheme());
418 if ($proxyConf === null) {
419 $proxyConf = '';
420 } elseif (($noProxy = \YoastSEO_Vendor\GuzzleHttp\Handler\ProxyEnvironment::getNoProxy()) !== null && \YoastSEO_Vendor\GuzzleHttp\Utils::isUriInNoProxy($request->getUri(), \YoastSEO_Vendor\GuzzleHttp\Handler\ProxyEnvironment::splitNoProxy($noProxy))) {
421 $proxyConf = '';
422 $noProxyConf = '*';
423 }
424 }
425 return [$proxyConf, $noProxyConf];
426 }
427 /**
428 * @param array<int|string, mixed> $conf
429 */
430 private static function rejectRequestLevelShareWithProxyAuth(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $options, array $conf) : void
431 {
432 if (!self::hasRequestLevelCurlShare($options)) {
433 return;
434 }
435 $proxy = self::getEffectiveProxy($conf);
436 if ($proxy === null) {
437 return;
438 }
439 // An external share handle may pool SOCKS connections where no section
440 // signature can reach them. On affected libcurl, even an anonymous
441 // request could inherit authenticated state already in that pool.
442 if (self::isSocksProxy($proxy, $conf)) {
443 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse()) {
444 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with SOCKS proxy configuration on libcurl before 7.69.0; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
445 }
446 if (self::hasAuthenticatedSocksProxyState($proxy, $conf)) {
447 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with authenticated SOCKS proxy configuration; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
448 }
449 }
450 if (!self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
451 return;
452 }
453 if (self::hasAuthenticatedHttpProxyState($proxy, $conf)) {
454 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with authenticated HTTP/HTTPS proxy tunnel configuration; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
455 }
456 // From libcurl 7.57.0 the external share can also own a connection
457 // cache seeded outside Guzzle with tunnel identity libcurl cannot
458 // key, so anonymous tunnels are rejected there too.
459 if (\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsShareConnectionCaches()) {
460 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with HTTP/HTTPS proxy tunnel configuration on libcurl 7.57.0 or newer; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
461 }
462 }
463 private static function hasRequestLevelCurlShare(array $options) : bool
464 {
465 return \defined('CURLOPT_SHARE') && isset($options['curl']) && \is_array($options['curl']) && \array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl']);
466 }
467 /**
468 * @param array<int|string, mixed> $conf
469 */
470 private static function hasAuthenticatedHttpProxyState(string $proxy, array $conf) : bool
471 {
472 $proxyForParsing = \strpos($proxy, '://') === \false ? 'http://' . $proxy : $proxy;
473 $proxyParts = \parse_url($proxyForParsing);
474 if (\is_array($proxyParts) && (\array_key_exists('user', $proxyParts) || \array_key_exists('pass', $proxyParts))) {
475 return \true;
476 }
477 if (self::hasCurlProxyCredentials($conf)) {
478 return \true;
479 }
480 if (self::hasCurlProxyAuthorizationHeader($conf)) {
481 return \true;
482 }
483 $httpHeaders = $conf[\CURLOPT_HTTPHEADER] ?? [];
484 if (\is_array($httpHeaders) && self::proxyAuthorizationHeaderValuesFromList($httpHeaders) !== []) {
485 return \true;
486 }
487 return self::hasCurlProxyTlsCredentials($conf);
488 }
489 /**
490 * @param int|string $option
491 */
492 private static function formatCurlOption($option) : string
493 {
494 if (!\is_int($option)) {
495 return \sprintf('"%s"', $option);
496 }
497 static $names = null;
498 if (null === $names) {
499 $names = [];
500 foreach (\get_defined_constants(\true)['curl'] ?? [] as $name => $value) {
501 if (\is_int($value) && \strpos($name, 'CURLOPT_') === 0 && !isset($names[$value])) {
502 $names[$value] = $name;
503 }
504 }
505 }
506 if (isset($names[$option])) {
507 return \sprintf('%s (%d)', $names[$option], $option);
508 }
509 return (string) $option;
510 }
511 private static function triggerConflictingCurlOptionDeprecations(array $options) : void
512 {
513 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
514 return;
515 }
516 $conflictingOptions = self::conflictingCurlOptions();
517 $sinceOverrides = self::conflictingCurlOptionSinceOverrides();
518 foreach ($options['curl'] as $option => $_) {
519 if (!\array_key_exists($option, $conflictingOptions)) {
520 continue;
521 }
522 $name = self::formatCurlOption($option);
523 $replacement = $conflictingOptions[$option];
524 $since = $sinceOverrides[$option] ?? '7.11';
525 if ($replacement !== null) {
526 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', $since, \sprintf('Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed request handling. Use %s instead.', $name, $replacement));
527 continue;
528 }
529 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', $since, \sprintf('Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed cURL internals.', $name));
530 }
531 }
532 private static function triggerUnsupportedCurlOptionDeprecations(array $options) : void
533 {
534 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
535 return;
536 }
537 if (\defined('CURLOPT_PROXYHEADER') && \array_key_exists((int) \constant('CURLOPT_PROXYHEADER'), $options['curl']) && !\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsProxyHeaderSeparation()) {
538 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', '7.15', \sprintf('Passing %s in the "curl" request option on a build without proxy header separation support is deprecated; guzzlehttp/guzzle 8.0 will reject this configuration because proxy headers require libcurl 7.37.0 or newer built with proxy header separation support.', self::formatCurlOption((int) \constant('CURLOPT_PROXYHEADER'))));
539 }
540 $supportedOptions = self::supportedCurlOptions();
541 $conflictingOptions = self::conflictingCurlOptions();
542 foreach ($options['curl'] as $option => $_) {
543 if (!\is_int($option) || \array_key_exists($option, $supportedOptions) || \array_key_exists($option, $conflictingOptions)) {
544 continue;
545 }
546 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', '7.12', \sprintf('Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject raw cURL options outside the built-in cURL handlers\' allow-list.', self::formatCurlOption($option)));
547 }
548 }
549 private static function triggerUnsupportedRequestOptionDeprecations(array $options) : void
550 {
551 if (\array_key_exists('stream_context', $options)) {
552 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "stream_context" request option to a cURL handler is deprecated; guzzlehttp/guzzle 8.0 will reject this option because cURL handlers ignore PHP stream context options.');
553 }
554 }
555 /**
556 * @return array<int, string|null>
557 */
558 private static function conflictingCurlOptions() : array
559 {
560 static $options = null;
561 if ($options !== null) {
562 return $options;
563 }
564 $options = [];
565 self::addConflictingCurlOption($options, 'CURLOPT_SHARE', 'the "transport_sharing" client option or cURL handler option');
566 self::addConflictingCurlOption($options, 'CURLOPT_URL', 'the request URI');
567 self::addConflictingCurlOption($options, 'CURLOPT_PORT', 'the request URI');
568 self::addConflictingCurlOption($options, 'CURLOPT_CUSTOMREQUEST', 'the request method');
569 self::addConflictingCurlOption($options, 'CURLOPT_HTTPGET', 'the request method');
570 self::addConflictingCurlOption($options, 'CURLOPT_POST', 'the request method and body');
571 self::addConflictingCurlOption($options, 'CURLOPT_PUT', 'the request method and body');
572 self::addConflictingCurlOption($options, 'CURLOPT_NOBODY', 'the request method');
573 self::addConflictingCurlOption($options, 'CURLOPT_UPLOAD', 'the request body');
574 self::addConflictingCurlOption($options, 'CURLOPT_POSTFIELDS', 'the request body');
575 self::addConflictingCurlOption($options, 'CURLOPT_READFUNCTION', 'the request body');
576 self::addConflictingCurlOption($options, 'CURLOPT_READDATA', 'the request body');
577 self::addConflictingCurlOption($options, 'CURLOPT_INFILE', 'the request body');
578 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE', 'the request body');
579 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE_LARGE', 'the request body');
580 self::addConflictingCurlOption($options, 'CURLOPT_HTTPHEADER', 'the request headers');
581 self::addConflictingCurlOption($options, 'CURLOPT_USERAGENT', 'the request headers');
582 self::addConflictingCurlOption($options, 'CURLOPT_REFERER', 'the request headers');
583 self::addConflictingCurlOption($options, 'CURLOPT_HEADERFUNCTION', 'the "on_headers" request option');
584 self::addConflictingCurlOption($options, 'CURLOPT_WRITEFUNCTION', 'the "sink" request option');
585 self::addConflictingCurlOption($options, 'CURLOPT_FILE', 'the "sink" request option');
586 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT', 'the "timeout" request option');
587 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT_MS', 'the "timeout" request option');
588 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT', 'the "connect_timeout" request option');
589 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT_MS', 'the "connect_timeout" request option');
590 self::addConflictingCurlOption($options, 'CURLOPT_NOSIGNAL', 'the "timeout" or "connect_timeout" request option');
591 self::addConflictingCurlOption($options, 'CURLOPT_NOPROGRESS', 'the "progress" request option');
592 self::addConflictingCurlOption($options, 'CURLOPT_PROGRESSFUNCTION', 'the "progress" request option');
593 self::addConflictingCurlOption($options, 'CURLOPT_XFERINFOFUNCTION', 'the "progress" request option');
594 self::addConflictingCurlOption($options, 'CURLOPT_VERBOSE', 'the "debug" request option');
595 self::addConflictingCurlOption($options, 'CURLOPT_STDERR', 'the "debug" request option');
596 self::addConflictingCurlOption($options, 'CURLOPT_PROXY', 'the "proxy" request option');
597 self::addConflictingCurlOption($options, 'CURLOPT_NOPROXY', 'the "proxy" request option');
598 self::addConflictingCurlOption($options, 'CURLOPT_PROXYTYPE', 'the "proxy" request option with a scheme-prefixed URL');
599 self::addConflictingCurlOption($options, 'CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option');
600 self::addConflictingCurlOption($options, 'CURLOPT_MAXREDIRS', 'the "allow_redirects" request option');
601 self::addConflictingCurlOption($options, 'CURLOPT_POSTREDIR', 'the "allow_redirects" request option');
602 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS', 'the "allow_redirects" request option');
603 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS_STR', 'the "allow_redirects" request option');
604 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS', 'the "protocols" request option');
605 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS_STR', 'the "protocols" request option');
606 self::addConflictingCurlOption($options, 'CURLOPT_HTTP_VERSION', 'the request protocol version');
607 self::addConflictingCurlOption($options, 'CURLOPT_PIPEWAIT', 'the "multiplex" request option');
608 self::addConflictingCurlOption($options, 'CURLOPT_IPRESOLVE', 'the "force_ip_resolve" request option');
609 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYPEER', 'the "verify" request option');
610 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYHOST', 'the "verify" request option');
611 self::addConflictingCurlOption($options, 'CURLOPT_CAINFO', 'the "verify" request option');
612 self::addConflictingCurlOption($options, 'CURLOPT_CAPATH', 'the "verify" request option');
613 self::addConflictingCurlOption($options, 'CURLOPT_SSLVERSION', 'the "crypto_method" or "crypto_method_max" request option');
614 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERT', 'the "cert" request option');
615 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTPASSWD', 'the "cert" request option');
616 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTTYPE', 'the "cert_type" request option');
617 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEY', 'the "ssl_key" request option');
618 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYPASSWD', 'the "ssl_key" request option');
619 self::addConflictingCurlOption($options, 'CURLOPT_KEYPASSWD', 'the "ssl_key" request option');
620 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYTYPE', 'the "ssl_key_type" request option');
621 self::addConflictingCurlOption($options, 'CURLOPT_COOKIE', 'the "Cookie" request header or Guzzle cookie middleware');
622 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEFILE', 'Guzzle cookie middleware');
623 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEJAR', 'Guzzle cookie middleware');
624 self::addConflictingCurlOption($options, 'CURLOPT_COOKIELIST', 'Guzzle cookie middleware');
625 self::addConflictingCurlOption($options, 'CURLOPT_COOKIESESSION', 'Guzzle cookie middleware');
626 return $options;
627 }
628 /**
629 * @return array<int, string>
630 */
631 private static function conflictingCurlOptionSinceOverrides() : array
632 {
633 static $options = null;
634 if ($options !== null) {
635 return $options;
636 }
637 $options = [];
638 if (\defined('CURLOPT_PROXYTYPE')) {
639 $options[\CURLOPT_PROXYTYPE] = '7.12';
640 }
641 if (\defined('CURLOPT_PIPEWAIT')) {
642 $options[\CURLOPT_PIPEWAIT] = '7.14';
643 }
644 return $options;
645 }
646 /**
647 * @return array<int, true>
648 */
649 private static function supportedCurlOptions() : array
650 {
651 static $options = null;
652 if ($options !== null) {
653 return $options;
654 }
655 $options = [];
656 self::addSupportedCurlOption($options, 'CURLOPT_ADDRESS_SCOPE');
657 self::addSupportedCurlOption($options, 'CURLOPT_CERTINFO');
658 self::addSupportedCurlOption($options, 'CURLOPT_CONNECT_TO');
659 self::addSupportedCurlOption($options, 'CURLOPT_DNS_CACHE_TIMEOUT');
660 self::addSupportedCurlOption($options, 'CURLOPT_DNS_INTERFACE');
661 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP4');
662 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP6');
663 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SERVERS');
664 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SHUFFLE_ADDRESSES');
665 self::addSupportedCurlOption($options, 'CURLOPT_ENCODING');
666 self::addSupportedCurlOption($options, 'CURLOPT_FORBID_REUSE');
667 self::addSupportedCurlOption($options, 'CURLOPT_FRESH_CONNECT');
668 self::addSupportedCurlOption($options, 'CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS');
669 self::addSupportedCurlOption($options, 'CURLOPT_HTTPAUTH');
670 self::addSupportedCurlOption($options, 'CURLOPT_INTERFACE');
671 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORT');
672 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORTRANGE');
673 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_LIMIT');
674 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_TIME');
675 self::addSupportedCurlOption($options, 'CURLOPT_MAXAGE_CONN');
676 self::addSupportedCurlOption($options, 'CURLOPT_MAXCONNECTS');
677 self::addSupportedCurlOption($options, 'CURLOPT_MAXLIFETIME_CONN');
678 self::addSupportedCurlOption($options, 'CURLOPT_HTTPPROXYTUNNEL');
679 self::addSupportedCurlOption($options, 'CURLOPT_PREREQFUNCTION');
680 self::addSupportedCurlOption($options, 'CURLOPT_PROXYHEADER');
681 self::addSupportedCurlOption($options, 'CURLOPT_PROXYUSERPWD');
682 self::addSupportedCurlOption($options, 'CURLOPT_RESOLVE');
683 self::addSupportedCurlOption($options, 'CURLOPT_SSL_CIPHER_LIST');
684 self::addSupportedCurlOption($options, 'CURLOPT_SSL_EC_CURVES');
685 self::addSupportedCurlOption($options, 'CURLOPT_TCP_FASTOPEN');
686 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPALIVE');
687 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPIDLE');
688 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPINTVL');
689 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPCNT');
690 self::addSupportedCurlOption($options, 'CURLOPT_TCP_NODELAY');
691 self::addSupportedCurlOption($options, 'CURLOPT_TLS13_CIPHERS');
692 self::addSupportedCurlOption($options, 'CURLOPT_UNIX_SOCKET_PATH');
693 self::addSupportedCurlOption($options, 'CURLOPT_USERPWD');
694 return $options;
695 }
696 /**
697 * @param array<int, true> $options
698 */
699 private static function addSupportedCurlOption(array &$options, string $constant) : void
700 {
701 if (!\defined($constant)) {
702 return;
703 }
704 $value = \constant($constant);
705 if (\is_int($value)) {
706 $options[$value] = \true;
707 }
708 }
709 /**
710 * @param array<int, string|null> $options
711 */
712 private static function addConflictingCurlOption(array &$options, string $constant, ?string $replacement) : void
713 {
714 if (!\defined($constant)) {
715 return;
716 }
717 $value = \constant($constant);
718 if (\is_int($value)) {
719 $options[$value] = $replacement;
720 }
721 }
722 public function release(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : void
723 {
724 $resource = $easy->handle;
725 unset($easy->handle);
726 if (\count($this->handles) >= $this->maxHandles || $easy->proxyTunnelSignature !== null && $easy->proxyTunnelSignature !== $this->proxyTunnelOwner) {
727 // Pool is full, or this handle belongs to a superseded tunnel
728 // owner (an async create/release overlap can hand a stale-owner
729 // handle back after a purge) - drop it instead of pooling it.
730 if (\PHP_VERSION_ID < 80000) {
731 \curl_close($resource);
732 }
733 return;
734 }
735 if ($easy->proxyTunnelSignature !== null) {
736 // A pooled handle now carries the current owner's tunnel.
737 $this->poolMayHoldTunnels = \true;
738 }
739 // Remove all callback functions as they can hold onto references and
740 // are not cleaned up by curl_reset. Using curl_setopt_array does not
741 // work for some reason, so removing each one individually.
742 \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null);
743 \curl_setopt($resource, \CURLOPT_READFUNCTION, null);
744 \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null);
745 \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null);
746 if (\defined('CURLOPT_PREREQFUNCTION')) {
747 \curl_setopt($resource, (int) \constant('CURLOPT_PREREQFUNCTION'), null);
748 }
749 \curl_reset($resource);
750 $this->handles[] = $resource;
751 }
752 /**
753 * Completes a cURL transaction, either returning a response promise or a
754 * rejected promise.
755 *
756 * @param callable(RequestInterface, array): PromiseInterface $handler
757 * @param CurlFactoryInterface $factory Dictates how the handle is released
758 */
759 public static function finish(callable $handler, \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, \YoastSEO_Vendor\GuzzleHttp\Handler\CurlFactoryInterface $factory) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
760 {
761 if (isset($easy->options['on_stats'])) {
762 try {
763 self::invokeStats($easy);
764 } catch (\Throwable $e) {
765 try {
766 $factory->release($easy);
767 } catch (\Throwable $releaseFailure) {
768 // Keep the on_stats throwable as the visible failure.
769 }
770 throw $e;
771 }
772 }
773 if (!$easy->response || $easy->errno) {
774 return self::finishError($handler, $easy, $factory);
775 }
776 // Return the response if it is present and there is no error.
777 $factory->release($easy);
778 // Rewind the body of the response if possible.
779 $body = $easy->response->getBody();
780 if ($body->isSeekable()) {
781 $body->rewind();
782 }
783 if (isset($easy->options['on_trailers'])) {
784 try {
785 $easy->options['on_trailers'](self::headersFromTrailerLines($easy->trailers), $easy->response);
786 } catch (\Throwable $e) {
787 return \YoastSEO_Vendor\GuzzleHttp\Promise\Create::rejectionFor(new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('An error was encountered during the on_trailers event', $easy->request, $easy->response, $e));
788 }
789 }
790 return new \YoastSEO_Vendor\GuzzleHttp\Promise\FulfilledPromise($easy->response);
791 }
792 private static function invokeStats(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : void
793 {
794 $curlStats = \curl_getinfo($easy->handle);
795 $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME);
796 $stats = new \YoastSEO_Vendor\GuzzleHttp\TransferStats($easy->request, $easy->response, $curlStats['total_time'], $easy->errno, $curlStats);
797 $easy->options['on_stats']($stats);
798 }
799 /**
800 * @param callable(RequestInterface, array): PromiseInterface $handler
801 */
802 private static function finishError(callable $handler, \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, \YoastSEO_Vendor\GuzzleHttp\Handler\CurlFactoryInterface $factory) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
803 {
804 // Get error information and release the handle to the factory.
805 $ctx = ['errno' => $easy->errno, 'error' => \curl_error($easy->handle), 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME)] + \curl_getinfo($easy->handle);
806 $ctx[self::CURL_VERSION_STR] = \YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::getVersion() ?? '';
807 $factory->release($easy);
808 // Retry when nothing is present or when curl failed to rewind.
809 if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) {
810 return self::retryFailedRewind($handler, $easy, $ctx);
811 }
812 return self::createRejection($easy, $ctx);
813 }
814 private static function createRejection(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array $ctx) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
815 {
816 static $connectionErrors = [\CURLE_OPERATION_TIMEOUTED => \true, \CURLE_COULDNT_RESOLVE_HOST => \true, \CURLE_COULDNT_CONNECT => \true, \CURLE_SSL_CONNECT_ERROR => \true, \CURLE_GOT_NOTHING => \true];
817 $uri = $easy->request->getUri();
818 // Redact the native error before it reaches any exception so the
819 // handler context matches the sanitized exception message.
820 $ctx['error'] = self::sanitizeCurlError((string) ($ctx['error'] ?? ''), $uri, $easy->effectiveProxy);
821 if ($easy->createResponseException) {
822 return \YoastSEO_Vendor\GuzzleHttp\Promise\Create::rejectionFor(new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('An error was encountered while creating the response', $easy->request, null, $easy->createResponseException, $ctx));
823 }
824 // If an exception was encountered during the onHeaders event, then
825 // return a rejected promise that wraps that exception.
826 if ($easy->onHeadersException) {
827 return \YoastSEO_Vendor\GuzzleHttp\Promise\Create::rejectionFor(new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('An error was encountered during the on_headers event', $easy->request, $easy->response, $easy->onHeadersException, $ctx));
828 }
829 $sanitizedError = $ctx['error'];
830 $message = \sprintf('cURL error %s: %s (%s)', $ctx['errno'], $sanitizedError, 'see https://curl.se/libcurl/c/libcurl-errors.html');
831 if ('' !== $sanitizedError) {
832 $redactedUriString = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::redactUserInfo($uri)->__toString();
833 if ($redactedUriString !== '' && \false === \strpos($sanitizedError, $redactedUriString)) {
834 $message .= \sprintf(' for %s', $redactedUriString);
835 }
836 }
837 // Create a connection exception if it was a specific error code.
838 $error = isset($connectionErrors[$easy->errno]) ? new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException($message, $easy->request, null, $ctx) : new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException($message, $easy->request, $easy->response, null, $ctx);
839 return \YoastSEO_Vendor\GuzzleHttp\Promise\Create::rejectionFor($error);
840 }
841 private static function sanitizeCurlError(string $error, \YoastSEO_Vendor\Psr\Http\Message\UriInterface $uri, ?string $proxy = null) : string
842 {
843 if ('' === $error) {
844 return $error;
845 }
846 $error = self::redactProxyUserInfo($error, $proxy);
847 $baseUri = $uri->withQuery('')->withFragment('');
848 $baseUriString = $baseUri->__toString();
849 if ('' === $baseUriString) {
850 return $error;
851 }
852 $redactedUriString = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::redactUserInfo($baseUri)->__toString();
853 return \str_replace($baseUriString, $redactedUriString, $error);
854 }
855 private static function redactProxyUserInfo(string $error, ?string $proxy) : string
856 {
857 if ($proxy === null || $proxy === '' || \strpos($proxy, '@') === \false) {
858 return $error;
859 }
860 // The error message embeds the proxy string exactly as configured, so
861 // the userinfo needle is taken verbatim from the raw string:
862 // parse_url() and Psr7\Uri normalize the components, e.g. by rewriting
863 // raw control bytes to '_', which could make the replacement miss.
864 $proxyForParsing = \strpos($proxy, '://') === \false ? 'http://' . $proxy : $proxy;
865 $remainder = \substr($proxyForParsing, \strpos($proxyForParsing, '://') + 3);
866 if (\parse_url($proxyForParsing) === \false) {
867 // Raw '/', '?', or '#' separators may sit inside the credentials
868 // of a proxy that defeats parse_url(), so the redaction cannot
869 // stop at the apparent authority.
870 $atPosition = \strrpos($remainder, '@');
871 if ($atPosition === \false || $atPosition === 0) {
872 return $error;
873 }
874 return \str_replace(\substr($remainder, 0, $atPosition) . '@', '***@', $error);
875 }
876 $authority = \substr($remainder, 0, \strcspn($remainder, '/?#'));
877 $atPosition = \strrpos($authority, '@');
878 if ($atPosition === \false || $atPosition === 0) {
879 // A parseable proxy URL with '@' only past its authority, or with
880 // an empty userinfo, carries no credentials to redact.
881 return $error;
882 }
883 $rawUserInfo = \substr($authority, 0, $atPosition);
884 // Redact with the same policy Psr7\Utils::redactUserInfo() applies to
885 // request URIs, so the bundled psr7 version governs the redacted form.
886 $redactedUserInfo = '***';
887 try {
888 $proxyUri = new \YoastSEO_Vendor\GuzzleHttp\Psr7\Uri($proxyForParsing);
889 $redactedUserInfo = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::redactUserInfo($proxyUri)->getUserInfo();
890 if ($redactedUserInfo === $proxyUri->getUserInfo()) {
891 return $error;
892 }
893 } catch (\InvalidArgumentException $e) {
894 // Unparseable as a URI: fall back to redacting the whole userinfo.
895 }
896 return \str_replace($rawUserInfo . '@', $redactedUserInfo . '@', $error);
897 }
898 /**
899 * @param array<int|string, mixed> $conf
900 */
901 private static function forceFreshConnectionForAuthenticatedProxy(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array &$conf) : void
902 {
903 $proxy = self::getEffectiveProxy($conf);
904 if ($proxy === null || !self::requiresFreshConnectionForAuthenticatedProxy($request, $proxy, $conf)) {
905 return;
906 }
907 $conf[\CURLOPT_FRESH_CONNECT] = \true;
908 $conf[\CURLOPT_FORBID_REUSE] = \true;
909 }
910 /**
911 * @param array<int|string, mixed> $conf
912 */
913 private function isolateOpaqueShareAnonymousProxyTunnel(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array &$conf) : void
914 {
915 if (!$this->opaqueShareConnectionCache || !\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsShareConnectionCaches()) {
916 return;
917 }
918 $proxy = self::getEffectiveProxy($conf);
919 if ($proxy === null || !self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf) || self::hasAuthenticatedHttpProxyState($proxy, $conf)) {
920 return;
921 }
922 // From libcurl 7.57.0 an opaque share handle can own a connection
923 // cache, and a tunnel seeded there with a literal Proxy-Authorization
924 // header is never keyed on credentials, so an anonymous request could
925 // inherit it on every later libcurl version. Requests carrying
926 // recognized credential state keep the version-gated channel
927 // safeguards above.
928 $conf[\CURLOPT_FRESH_CONNECT] = \true;
929 $conf[\CURLOPT_FORBID_REUSE] = \true;
930 }
931 /**
932 * @param array<int|string, mixed> $conf
933 */
934 private static function assertFinalProxyOptionTypes(array $conf, bool $requiredCleartextMultiplex) : void
935 {
936 if (\array_key_exists(\CURLOPT_PROXYTYPE, $conf) && !\is_int($conf[\CURLOPT_PROXYTYPE])) {
937 throw new \InvalidArgumentException('CURLOPT_PROXYTYPE must be an integer.');
938 }
939 foreach (['CURLOPT_PROXY', 'CURLOPT_NOPROXY', 'CURLOPT_PRE_PROXY'] as $name) {
940 if (!\defined($name)) {
941 continue;
942 }
943 $option = (int) \constant($name);
944 if (\array_key_exists($option, $conf) && !\is_string($conf[$option])) {
945 if ($requiredCleartextMultiplex) {
946 throw new \InvalidArgumentException(\sprintf('The "multiplex" request option cannot be required when the final %s cURL option value is not a string.', $name));
947 }
948 throw new \InvalidArgumentException($name . ' must be a string.');
949 }
950 }
951 }
952 /**
953 * @param array<int|string, mixed> $conf
954 */
955 private static function isolatePreProxyOnAffectedCurl(array &$conf) : void
956 {
957 if (\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse() || !\defined('CURLOPT_PRE_PROXY')) {
958 return;
959 }
960 $option = (int) \constant('CURLOPT_PRE_PROXY');
961 if (!\array_key_exists($option, $conf) || $conf[$option] === '') {
962 return;
963 }
964 $conf[\CURLOPT_FRESH_CONNECT] = \true;
965 $conf[\CURLOPT_FORBID_REUSE] = \true;
966 }
967 /**
968 * @param array<int|string, mixed> $conf
969 */
970 private static function getEffectiveProxy(array $conf) : ?string
971 {
972 if (!\array_key_exists(\CURLOPT_PROXY, $conf)) {
973 return null;
974 }
975 $proxy = $conf[\CURLOPT_PROXY];
976 if (!\is_string($proxy) || $proxy === '') {
977 return null;
978 }
979 // Only the exact raw wildcard is modeled here: libcurl treats '*' as
980 // bypass-all by whole-string comparison, without trimming or host matching.
981 if (\defined('CURLOPT_NOPROXY')) {
982 $noProxy = $conf[(int) \constant('CURLOPT_NOPROXY')] ?? null;
983 if (\is_string($noProxy) && $noProxy === '*') {
984 return null;
985 }
986 }
987 return $proxy;
988 }
989 /**
990 * @param array<int|string, mixed> $conf
991 */
992 private static function normalizeCurlHeaderOptions(array &$conf) : void
993 {
994 $options = [\CURLOPT_HTTPHEADER => 'CURLOPT_HTTPHEADER'];
995 if (\defined('CURLOPT_PROXYHEADER')) {
996 $options[(int) \constant('CURLOPT_PROXYHEADER')] = 'CURLOPT_PROXYHEADER';
997 }
998 foreach ($options as $option => $label) {
999 if (!\array_key_exists($option, $conf) || !\is_array($conf[$option])) {
1000 continue;
1001 }
1002 $normalized = [];
1003 foreach ($conf[$option] as $key => $entry) {
1004 if (\is_object($entry) && \method_exists($entry, '__toString')) {
1005 $entry = (string) $entry;
1006 } elseif (\is_float($entry) && !\is_finite($entry)) {
1007 $entry = \is_nan($entry) ? 'NAN' : ($entry > 0 ? 'INF' : '-INF');
1008 } elseif (\is_scalar($entry)) {
1009 $entry = (string) $entry;
1010 } else {
1011 throw new \InvalidArgumentException(\sprintf('%s entries must be strings, stringable objects, or scalar values.', $label));
1012 }
1013 if (\strpbrk($entry, "\r\n") !== \false) {
1014 throw new \InvalidArgumentException(\sprintf('%s entries must not contain a carriage return or line feed.', $label));
1015 }
1016 $normalized[$key] = $entry;
1017 }
1018 $conf[$option] = $normalized;
1019 }
1020 }
1021 private static function proxyScheme(string $proxy) : ?string
1022 {
1023 $position = \strpos($proxy, '://');
1024 return $position === \false ? null : \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToLower(\substr($proxy, 0, $position));
1025 }
1026 /**
1027 * @param array<int|string, mixed> $conf
1028 */
1029 private static function requiresFreshConnectionForAuthenticatedProxy(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, string $proxy, array $conf) : bool
1030 {
1031 // SOCKS authentication binds an identity to the connection itself, and
1032 // below 7.69.0 an opaque configured share may already contain a SOCKS
1033 // connection whose credential state Guzzle cannot inspect. Isolate
1034 // authenticated and anonymous requests so neither can inherit it.
1035 if (self::isSocksProxy($proxy, $conf)) {
1036 return !\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse();
1037 }
1038 if (!self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
1039 return \false;
1040 }
1041 $proxyForParsing = \strpos($proxy, '://') === \false ? 'http://' . $proxy : $proxy;
1042 $proxyParts = \parse_url($proxyForParsing);
1043 if (!\is_array($proxyParts)) {
1044 return \false;
1045 }
1046 if (self::hasCurlProxyAuthorizationHeader($conf)) {
1047 return \true;
1048 }
1049 // A proxy client certificate or TLS-SRP authenticates the client to the
1050 // HTTPS proxy at the TLS layer; libcurl ignored TLS-SRP before 7.83.1
1051 // (CVE-2022-27782), so an old build can reuse a tunnel across those
1052 // identities. Force a fresh one, as the non-share signature path does.
1053 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsProxyTlsCredentialAwareConnectionReuse() && self::hasCurlProxyTlsCredentials($conf)) {
1054 return \true;
1055 }
1056 if (\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsProxyCredentialAwareConnectionReuse()) {
1057 return \false;
1058 }
1059 return \array_key_exists('user', $proxyParts) || \array_key_exists('pass', $proxyParts) || self::hasCurlProxyCredentials($conf);
1060 }
1061 /**
1062 * @param array<int|string, mixed> $conf
1063 */
1064 private static function hasAuthenticatedSocksProxyState(string $proxy, array $conf) : bool
1065 {
1066 $proxyForParsing = \strpos($proxy, '://') === \false ? 'http://' . $proxy : $proxy;
1067 $proxyParts = \parse_url($proxyForParsing);
1068 if (\is_array($proxyParts) && (\array_key_exists('user', $proxyParts) || \array_key_exists('pass', $proxyParts))) {
1069 return \true;
1070 }
1071 return self::hasCurlProxyCredentials($conf);
1072 }
1073 /**
1074 * @param array<int|string, mixed> $conf
1075 */
1076 private static function usesProxyTunnel(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $conf) : bool
1077 {
1078 $scheme = $request->getUri()->getScheme();
1079 if ('https' === $scheme) {
1080 return \true;
1081 }
1082 // An HTTP proxy auto-switches to a CONNECT tunnel when CONNECT_TO
1083 // redirects the origin, so an http:// target with it set tunnels too.
1084 if ('http' === $scheme && self::hasCurlConnectTo($conf)) {
1085 return \true;
1086 }
1087 return \defined('CURLOPT_HTTPPROXYTUNNEL') && \array_key_exists((int) \constant('CURLOPT_HTTPPROXYTUNNEL'), $conf) && (bool) $conf[(int) \constant('CURLOPT_HTTPPROXYTUNNEL')];
1088 }
1089 /**
1090 * @param array<int|string, mixed> $conf
1091 */
1092 private static function hasCurlConnectTo(array $conf) : bool
1093 {
1094 if (!\defined('CURLOPT_CONNECT_TO')) {
1095 return \false;
1096 }
1097 $option = (int) \constant('CURLOPT_CONNECT_TO');
1098 if (!\array_key_exists($option, $conf)) {
1099 return \false;
1100 }
1101 $value = $conf[$option];
1102 return \is_array($value) ? $value !== [] : $value !== null && $value !== \false && $value !== '';
1103 }
1104 /**
1105 * @param array<int|string, mixed> $conf
1106 */
1107 private static function isHttpProxyForConnectionReuse(string $proxy, array $conf) : bool
1108 {
1109 if (\strpos($proxy, '://') !== \false) {
1110 $proxyParts = \parse_url($proxy);
1111 if (!\is_array($proxyParts) || !isset($proxyParts['scheme'])) {
1112 return \false;
1113 }
1114 $proxyScheme = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToLower($proxyParts['scheme']);
1115 return $proxyScheme === 'http' || $proxyScheme === 'https';
1116 }
1117 return !self::isSocksProxyType($conf[\CURLOPT_PROXYTYPE] ?? null);
1118 }
1119 /**
1120 * @param array<int|string, mixed> $conf
1121 */
1122 private static function isSocksProxy(string $proxy, array $conf) : bool
1123 {
1124 $scheme = self::proxyScheme($proxy);
1125 if ($scheme !== null) {
1126 if (\in_array($scheme, ['socks', 'socks4', 'socks4a', 'socks5', 'socks5h'], \true)) {
1127 return \true;
1128 }
1129 // libcurl preserves a raw SOCKS CURLOPT_PROXYTYPE behind an http
1130 // scheme, while every other scheme overrides the proxy type.
1131 if ($scheme !== 'http') {
1132 return \false;
1133 }
1134 }
1135 return self::isSocksProxyType($conf[\CURLOPT_PROXYTYPE] ?? null);
1136 }
1137 /**
1138 * Computes the connection-reuse section signature for a SOCKS proxy.
1139 * libcurl compares SOCKS credentials on connection reuse from 7.69.0 (curl
1140 * #4835), so no sectioning is needed there. Older libcurl matches a SOCKS
1141 * proxy by type, host, and port only, so every SOCKS request is sectioned
1142 * by its credential state; hashing the credential-less state too keeps an
1143 * unauthenticated request from inheriting an authenticated connection.
1144 *
1145 * @param array<int|string, mixed> $conf
1146 */
1147 private static function socksProxySignature(string $proxy, array $conf) : ?string
1148 {
1149 if (\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse()) {
1150 return null;
1151 }
1152 $credentialState = [];
1153 foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD', 'CURLOPT_PROXYTYPE'] as $name) {
1154 $credentialState[$name] = \defined($name) ? $conf[(int) \constant($name)] ?? null : null;
1155 }
1156 return \hash('sha256', \serialize(['socks', $proxy, $credentialState]));
1157 }
1158 /**
1159 * @param mixed $proxyType
1160 */
1161 private static function isSocksProxyType($proxyType) : bool
1162 {
1163 if (!\is_int($proxyType)) {
1164 return \false;
1165 }
1166 foreach (['CURLPROXY_SOCKS4' => 4, 'CURLPROXY_SOCKS5' => 5, 'CURLPROXY_SOCKS4A' => 6, 'CURLPROXY_SOCKS5_HOSTNAME' => 7] as $name => $fallback) {
1167 $value = \defined($name) ? (int) \constant($name) : $fallback;
1168 if ($proxyType === $value) {
1169 return \true;
1170 }
1171 }
1172 return \false;
1173 }
1174 /**
1175 * @param array<int|string, mixed> $conf
1176 */
1177 private static function hasCurlProxyCredentials(array $conf) : bool
1178 {
1179 foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD'] as $option) {
1180 if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) {
1181 return \true;
1182 }
1183 }
1184 return \false;
1185 }
1186 /**
1187 * @param array<int|string, mixed> $conf
1188 */
1189 private static function hasCurlProxyTlsCredentials(array $conf) : bool
1190 {
1191 foreach (['CURLOPT_PROXY_SSLCERT', 'CURLOPT_PROXY_SSLCERT_BLOB', 'CURLOPT_PROXY_TLSAUTH_USERNAME', 'CURLOPT_PROXY_TLSAUTH_PASSWORD'] as $option) {
1192 if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) {
1193 return \true;
1194 }
1195 }
1196 return \false;
1197 }
1198 /**
1199 * @param array<int|string, mixed> $conf
1200 */
1201 private static function hasCurlProxyAuthorizationHeader(array $conf) : bool
1202 {
1203 return self::curlProxyAuthorizationHeaderValues($conf) !== [];
1204 }
1205 /**
1206 * @param array<int|string, mixed> $conf
1207 */
1208 private static function applyProxyAuthorizationHeaderHandling(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array &$conf) : void
1209 {
1210 $proxy = self::getEffectiveProxy($conf);
1211 if ($proxy === null || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
1212 return;
1213 }
1214 $httpHeaders = $conf[\CURLOPT_HTTPHEADER] ?? null;
1215 $movedHeaders = [];
1216 $originHeaders = [];
1217 if (\is_array($httpHeaders)) {
1218 foreach ($httpHeaders as $header) {
1219 if (\is_string($header) && self::isProxyAuthorizationHeaderLine($header)) {
1220 $movedHeaders[] = $header;
1221 continue;
1222 }
1223 $originHeaders[] = $header;
1224 }
1225 }
1226 if (\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsProxyHeaderSeparation()) {
1227 if ($movedHeaders !== []) {
1228 $conf[\CURLOPT_HTTPHEADER] = $originHeaders;
1229 self::appendCurlProxyHeaders($conf, $movedHeaders);
1230 }
1231 // On libcurl 7.37.0-7.42.0 the default is CURLHEADER_UNIFIED.
1232 if ($movedHeaders !== [] || self::hasCurlProxyHeaderOption($conf) || self::usesProxyTunnel($request, $conf)) {
1233 $conf[(int) \constant('CURLOPT_HEADEROPT')] = (int) \constant('CURLHEADER_SEPARATE');
1234 }
1235 return;
1236 }
1237 if (\is_array($httpHeaders) && self::proxyAuthorizationHeaderValuesFromList($httpHeaders) !== []) {
1238 $conf[\CURLOPT_FRESH_CONNECT] = \true;
1239 $conf[\CURLOPT_FORBID_REUSE] = \true;
1240 }
1241 }
1242 /**
1243 * Routes the managed first-class Proxy-Authorization values to libcurl's
1244 * proxy-only header channel, independently of Guzzle's proxy prediction:
1245 * libcurl alone decides whether the proxy-only list is used for the
1246 * actual transfer, so the credential can never reach an origin through
1247 * CURLOPT_HTTPHEADER. Without proxy header separation support, values are
1248 * safely omitted on known direct, bypassed, and SOCKS routes; a route that
1249 * may use an HTTP(S) proxy is rejected before cURL initialization and
1250 * network I/O. A deprecated raw CURLOPT_HTTPHEADER replacement suppresses
1251 * every generated header, the managed values included.
1252 *
1253 * @param array<int|string, mixed> $conf
1254 * @param list<string> $headers
1255 */
1256 private static function applyManagedProxyAuthorization(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array &$conf, array $headers, bool $rawHttpHeadersReplaceManaged) : void
1257 {
1258 if ($rawHttpHeadersReplaceManaged || $headers === []) {
1259 return;
1260 }
1261 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsProxyHeaderSeparation()) {
1262 $proxy = self::getEffectiveProxy($conf);
1263 if ($proxy !== null && !self::isSocksProxy($proxy, $conf)) {
1264 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('Proxy-Authorization request headers through a possible HTTP or HTTPS proxy require libcurl 7.37.0 or newer built with proxy header separation support.', $request);
1265 }
1266 return;
1267 }
1268 self::appendCurlProxyHeaders($conf, $headers);
1269 $conf[(int) \constant('CURLOPT_HEADEROPT')] = (int) \constant('CURLHEADER_SEPARATE');
1270 }
1271 /**
1272 * @return list<string>
1273 */
1274 private static function managedProxyAuthorizationHeaderLines(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request) : array
1275 {
1276 $headers = [];
1277 foreach ($request->getHeader('Proxy-Authorization') as $value) {
1278 $headers[] = $value === '' ? 'Proxy-Authorization;' : 'Proxy-Authorization: ' . $value;
1279 }
1280 return $headers;
1281 }
1282 /**
1283 * @param array<int|string, mixed> $conf
1284 * @param list<string> $headers
1285 */
1286 private static function appendCurlProxyHeaders(array &$conf, array $headers) : void
1287 {
1288 $option = (int) \constant('CURLOPT_PROXYHEADER');
1289 if (\array_key_exists($option, $conf)) {
1290 if (!\is_array($conf[$option])) {
1291 throw new \InvalidArgumentException('CURLOPT_PROXYHEADER must be an array when a Proxy-Authorization request header is routed to the proxy header channel.');
1292 }
1293 $headers = \array_merge($conf[$option], $headers);
1294 }
1295 $conf[$option] = $headers;
1296 }
1297 /**
1298 * @param array<int|string, mixed> $conf
1299 */
1300 private static function hasCurlProxyHeaderOption(array $conf) : bool
1301 {
1302 return \defined('CURLOPT_PROXYHEADER') && \array_key_exists((int) \constant('CURLOPT_PROXYHEADER'), $conf);
1303 }
1304 private static function isProxyAuthorizationHeaderLine(string $header) : bool
1305 {
1306 $length = \strcspn($header, ':;');
1307 if ($length === \strlen($header)) {
1308 return \false;
1309 }
1310 return \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::caselessEquals(\trim(\substr($header, 0, $length), " \n\r\t\x00\v"), 'Proxy-Authorization');
1311 }
1312 private static function proxyAuthorizationHeaderValue(string $header) : ?string
1313 {
1314 $position = \strpos($header, ':');
1315 if ($position === \false) {
1316 return null;
1317 }
1318 if (!\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::caselessEquals(\trim(\substr($header, 0, $position), " \n\r\t\x00\v"), 'Proxy-Authorization')) {
1319 return null;
1320 }
1321 $value = \trim(\substr($header, $position + 1), " \n\r\t\x00\v");
1322 return $value === '' ? null : $value;
1323 }
1324 /**
1325 * @param mixed[] $headers
1326 *
1327 * @return list<string>
1328 */
1329 private static function proxyAuthorizationHeaderValuesFromList(array $headers) : array
1330 {
1331 $values = [];
1332 foreach ($headers as $header) {
1333 if (!\is_string($header)) {
1334 continue;
1335 }
1336 $value = self::proxyAuthorizationHeaderValue($header);
1337 if ($value !== null) {
1338 $values[] = $value;
1339 }
1340 }
1341 return $values;
1342 }
1343 /**
1344 * Computes the connection-reuse section signature for a proxy tunnel or
1345 * SOCKS proxy, or null when the request does not require sectioning.
1346 *
1347 * @param array<int|string, mixed> $conf
1348 */
1349 private static function proxyTunnelSignature(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $conf) : ?string
1350 {
1351 $proxy = self::getEffectiveProxy($conf);
1352 if ($proxy === null) {
1353 return null;
1354 }
1355 // SOCKS authentication binds an identity to the connection itself, for
1356 // plain http:// requests as much as https://, so it sections ahead of
1357 // the CONNECT tunnel domain checks.
1358 if (self::isSocksProxy($proxy, $conf)) {
1359 return self::socksProxySignature($proxy, $conf);
1360 }
1361 if (!self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
1362 return null;
1363 }
1364 $headerAuth = self::curlProxyAuthorizationHeaderValues($conf);
1365 if ($headerAuth === [] && \YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsProxyCredentialAwareConnectionReuse()) {
1366 // libcurl keys reuse on parsed proxy credentials only from 8.19.0,
1367 // trusted from 8.20.0 (PROXY_CREDENTIAL_REUSE_VERSION); a literal
1368 // Proxy-Authorization header is never keyed and always sections.
1369 return self::DELEGATED_PROXY_TUNNEL_OWNER;
1370 }
1371 // Hash every proxy channel an old libcurl might not key reuse on. A
1372 // changed signature only forces a fresh connection, never relaxes
1373 // reuse, so over-covering is always safe; under-covering leaks. Proxy
1374 // credentials are the channel CVE-2026-3784 missed; the proxy-TLS
1375 // options are load-bearing on builds before the proxy-TLS reuse fixes
1376 // (the proxy client cert is keyed from 7.52.0, libcurl's first
1377 // HTTPS-proxy release; CVE-2016-5420 (7.50.1) is only the origin-cert
1378 // precedent; TLS-SRP from 7.83.1, CVE-2022-27782) and harmless after.
1379 // The private-key file and passphrase are hashed on this non-delegated
1380 // path too, as fallback hardening: libcurl's mTLS private-key matching
1381 // on reuse was incomplete before 8.21.0 (CVE-2026-8932). This does not
1382 // cover the delegated path (the early return above) or configured share
1383 // handles, so it is not a complete pre-8.21.0 mitigation. The key blob
1384 // and cert/key type encodings (PROXY_SSLKEY_BLOB, PROXY_SSLKEYTYPE,
1385 // PROXY_SSLCERTTYPE) are not hashed and are an accepted residual.
1386 $credentialState = [];
1387 foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD', 'CURLOPT_PROXYTYPE', 'CURLOPT_PROXY_SSLCERT', 'CURLOPT_PROXY_SSLCERT_BLOB', 'CURLOPT_PROXY_SSLKEY', 'CURLOPT_PROXY_KEYPASSWD', 'CURLOPT_PROXY_TLSAUTH_USERNAME', 'CURLOPT_PROXY_TLSAUTH_PASSWORD', 'CURLOPT_PROXY_SSLVERSION'] as $name) {
1388 $credentialState[$name] = \defined($name) ? $conf[(int) \constant($name)] ?? null : null;
1389 }
1390 return \hash('sha256', \serialize([$proxy, $credentialState, $headerAuth]));
1391 }
1392 /**
1393 * @param array<int|string, mixed> $conf
1394 *
1395 * @return list<string>
1396 */
1397 private static function curlProxyAuthorizationHeaderValues(array $conf) : array
1398 {
1399 if (!\defined('CURLOPT_PROXYHEADER')) {
1400 return [];
1401 }
1402 $option = (int) \constant('CURLOPT_PROXYHEADER');
1403 if (!\array_key_exists($option, $conf)) {
1404 return [];
1405 }
1406 $headers = $conf[$option];
1407 if (!\is_array($headers)) {
1408 return [];
1409 }
1410 return self::proxyAuthorizationHeaderValuesFromList($headers);
1411 }
1412 private function discardIdleHandles() : void
1413 {
1414 foreach ($this->handles as $id => $handle) {
1415 if (\PHP_VERSION_ID < 80000) {
1416 \curl_close($handle);
1417 }
1418 unset($this->handles[$id]);
1419 }
1420 }
1421 /**
1422 * @return array<int|string, mixed>
1423 */
1424 private function getDefaultConf(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : array
1425 {
1426 $uri = $easy->request->getUri();
1427 $protocols = \YoastSEO_Vendor\GuzzleHttp\Utils::normalizeProtocols($easy->options['protocols'] ?? ['http', 'https']);
1428 $scheme = $uri->getScheme();
1429 if (!\in_array($scheme, $protocols, \true)) {
1430 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $easy->request);
1431 }
1432 if ($uri->getHost() === '') {
1433 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $easy->request);
1434 }
1435 $conf = ['_headers' => $easy->request->getHeaders(), \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), \CURLOPT_URL => (string) $uri->withFragment(''), \CURLOPT_RETURNTRANSFER => \false, \CURLOPT_HEADER => \false, \CURLOPT_CONNECTTIMEOUT => 300];
1436 if (\defined('CURLOPT_PROTOCOLS')) {
1437 $conf[\CURLOPT_PROTOCOLS] = self::curlProtocolMask($protocols);
1438 }
1439 $version = $easy->request->getProtocolVersion();
1440 $multiplex = self::normalizeMultiplex($easy->options);
1441 if ('2' === $version || '2.0' === $version) {
1442 if (\in_array($multiplex, [\YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_EAGER, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_WAIT], \true)) {
1443 self::assertRequiredMultiplexSupported($easy);
1444 // New HTTP/2 connections cannot negotiate HTTP/1.x here, and
1445 // the 8.14.0 floor's version-aware reuse matching keeps
1446 // reused connections on HTTP/2 as well.
1447 $conf[\CURLOPT_HTTP_VERSION] = (int) \constant('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE');
1448 } else {
1449 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
1450 }
1451 if (\in_array($multiplex, [\YoastSEO_Vendor\GuzzleHttp\Multiplexing::WAIT, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_WAIT], \true) && \YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsMultiplex()) {
1452 // Wait for a connection that is still being established to the
1453 // same origin to reveal whether it can be multiplexed instead
1454 // of immediately opening another connection.
1455 $conf[(int) \constant('CURLOPT_PIPEWAIT')] = \true;
1456 }
1457 } elseif ('1.1' === $version) {
1458 if (\in_array($multiplex, [\YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_EAGER, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_WAIT], \true)) {
1459 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException(\sprintf('The "multiplex" request option cannot be required for HTTP/%s requests; use protocol version 2.', $version), $easy->request);
1460 }
1461 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
1462 } else {
1463 if (\in_array($multiplex, [\YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_EAGER, \YoastSEO_Vendor\GuzzleHttp\Multiplexing::REQUIRE_WAIT], \true)) {
1464 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException(\sprintf('The "multiplex" request option cannot be required for HTTP/%s requests; use protocol version 2.', $version), $easy->request);
1465 }
1466 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
1467 }
1468 return $conf;
1469 }
1470 /**
1471 * @param string[] $protocols
1472 */
1473 private static function curlProtocolMask(array $protocols) : int
1474 {
1475 $mask = 0;
1476 if (\in_array('http', $protocols, \true)) {
1477 $mask |= \CURLPROTO_HTTP;
1478 }
1479 if (\in_array('https', $protocols, \true)) {
1480 $mask |= \CURLPROTO_HTTPS;
1481 }
1482 return $mask;
1483 }
1484 /**
1485 * @param mixed $type
1486 */
1487 private static function normalizeTlsFileType(string $option, $type) : string
1488 {
1489 if (!\is_string($type) || $type === '') {
1490 throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
1491 }
1492 return \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToUpper($type);
1493 }
1494 private static function shouldValidateSslKeyFile(?string $type) : bool
1495 {
1496 return $type !== 'ENG' && $type !== 'PROV';
1497 }
1498 private function applyMethod(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) : void
1499 {
1500 if ($easy->request->getMethod() === 'HEAD') {
1501 // libcurl stops at HEAD response headers only when CURLOPT_NOBODY
1502 // is set; CURLOPT_CUSTOMREQUEST changes only the method string.
1503 // NOBODY also suppresses request upload, so strip non-zero body
1504 // length, transfer coding, and a 100-continue expectation.
1505 $conf[\CURLOPT_CUSTOMREQUEST] = null;
1506 $conf[\CURLOPT_NOBODY] = \true;
1507 unset($conf[\CURLOPT_WRITEFUNCTION], $conf[\CURLOPT_READFUNCTION], $conf[\CURLOPT_FILE], $conf[\CURLOPT_INFILE]);
1508 if (\trim($easy->request->getHeaderLine('Content-Length'), " \n\r\t\x00\v") !== '0') {
1509 $this->removeHeader('Content-Length', $conf);
1510 }
1511 $this->removeHeader('Transfer-Encoding', $conf);
1512 if (\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::caselessEquals(\trim($easy->request->getHeaderLine('Expect'), " \n\r\t\x00\v"), '100-continue')) {
1513 $this->removeHeader('Expect', $conf);
1514 }
1515 return;
1516 }
1517 $body = $easy->request->getBody();
1518 $size = $body->getSize();
1519 if ($size === null || $size > 0) {
1520 $this->applyBody($easy->request, $easy->options, $conf);
1521 return;
1522 }
1523 $method = $easy->request->getMethod();
1524 if ($method === 'PUT' || $method === 'POST') {
1525 // See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
1526 if (!$easy->request->hasHeader('Content-Length')) {
1527 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
1528 }
1529 }
1530 }
1531 private function applyBody(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $options, array &$conf) : void
1532 {
1533 $size = $request->hasHeader('Content-Length') ? (int) $request->getHeaderLine('Content-Length') : null;
1534 // Send the body as a string if the size is less than 1MB OR if the
1535 // [curl][body_as_string] request value is set.
1536 if ($size !== null && $size < 1000000 || !empty($options['_body_as_string'])) {
1537 $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody();
1538 // Don't duplicate the Content-Length header
1539 $this->removeHeader('Content-Length', $conf);
1540 $this->removeHeader('Transfer-Encoding', $conf);
1541 } else {
1542 $conf[\CURLOPT_UPLOAD] = \true;
1543 if ($size !== null) {
1544 $conf[\CURLOPT_INFILESIZE] = $size;
1545 $this->removeHeader('Content-Length', $conf);
1546 }
1547 $body = $request->getBody();
1548 if ($body->isSeekable()) {
1549 $body->rewind();
1550 }
1551 $remaining = $size;
1552 $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use($body, &$remaining) {
1553 if ($remaining === 0) {
1554 return '';
1555 }
1556 $limit = $remaining === null ? $length : \min($length, $remaining);
1557 $data = $body->read($limit);
1558 if ($remaining !== null) {
1559 $remaining -= \strlen($data);
1560 }
1561 return $data;
1562 };
1563 }
1564 // If the Expect header is not present, prevent curl from adding it
1565 if (!$request->hasHeader('Expect')) {
1566 $conf[\CURLOPT_HTTPHEADER][] = 'Expect:';
1567 }
1568 // cURL sometimes adds a content-type by default. Prevent this.
1569 if (!$request->hasHeader('Content-Type')) {
1570 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:';
1571 }
1572 }
1573 private function applyHeaders(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) : void
1574 {
1575 foreach ($conf['_headers'] as $name => $values) {
1576 // A first-class Proxy-Authorization header is proxy-scoped and
1577 // must never be generated in the origin header list; managed
1578 // handling routes it to CURLOPT_PROXYHEADER or safely omits it on
1579 // a legacy non-HTTP-proxy route. The
1580 // caselessEquals() helper is locale-independent, unlike
1581 // strcasecmp(), so a locale cannot make this match miss and
1582 // re-leak the credential.
1583 if (\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::caselessEquals((string) $name, 'Proxy-Authorization')) {
1584 continue;
1585 }
1586 foreach ($values as $value) {
1587 $value = (string) $value;
1588 if ($value === '') {
1589 // cURL requires a special format for empty headers.
1590 // See https://github.com/guzzle/guzzle/issues/1882 for more details.
1591 $conf[\CURLOPT_HTTPHEADER][] = "{$name};";
1592 } else {
1593 $conf[\CURLOPT_HTTPHEADER][] = "{$name}: {$value}";
1594 }
1595 }
1596 }
1597 // Remove the Accept header if one was not set
1598 if (!$easy->request->hasHeader('Accept')) {
1599 $conf[\CURLOPT_HTTPHEADER][] = 'Accept:';
1600 }
1601 }
1602 /**
1603 * Remove a header from the options array.
1604 *
1605 * @param string $name Case-insensitive header to remove
1606 * @param array $options Array of options to modify
1607 */
1608 private function removeHeader(string $name, array &$options) : void
1609 {
1610 foreach (\array_keys($options['_headers']) as $key) {
1611 if (\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::caselessEquals((string) $key, $name)) {
1612 unset($options['_headers'][$key]);
1613 return;
1614 }
1615 }
1616 }
1617 private function applyHandlerOptions(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) : void
1618 {
1619 $options = $easy->options;
1620 if (isset($options['verify'])) {
1621 if ($options['verify'] === \false) {
1622 unset($conf[\CURLOPT_CAINFO]);
1623 $conf[\CURLOPT_SSL_VERIFYHOST] = 0;
1624 $conf[\CURLOPT_SSL_VERIFYPEER] = \false;
1625 } else {
1626 $conf[\CURLOPT_SSL_VERIFYHOST] = 2;
1627 $conf[\CURLOPT_SSL_VERIFYPEER] = \true;
1628 if (\is_string($options['verify'])) {
1629 // Throw an error if the file/folder/link path is not valid or doesn't exist.
1630 if (!\file_exists($options['verify'])) {
1631 throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}");
1632 }
1633 // If it's a directory or a link to a directory use CURLOPT_CAPATH.
1634 // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO.
1635 if (\is_dir($options['verify']) || \is_link($options['verify']) === \true && ($verifyLink = \readlink($options['verify'])) !== \false && \is_dir($verifyLink)) {
1636 $conf[\CURLOPT_CAPATH] = $options['verify'];
1637 } else {
1638 $conf[\CURLOPT_CAINFO] = $options['verify'];
1639 }
1640 }
1641 }
1642 }
1643 if (!isset($options['curl'][\CURLOPT_ENCODING]) && isset($options['decode_content']) && $options['decode_content'] !== \false) {
1644 $accept = $easy->request->getHeaderLine('Accept-Encoding');
1645 if ($accept !== '') {
1646 $conf[\CURLOPT_ENCODING] = $accept;
1647 } else {
1648 // The empty string enables all available decoders and implicitly
1649 // sets a matching 'Accept-Encoding' header.
1650 $conf[\CURLOPT_ENCODING] = '';
1651 // But as the user did not specify any encoding preference,
1652 // let's leave it up to server by preventing curl from sending
1653 // the header, which will be interpreted as 'Accept-Encoding: *'.
1654 // https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
1655 $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
1656 }
1657 }
1658 if (!isset($options['sink'])) {
1659 // Use a default temp stream if no sink was set.
1660 $options['sink'] = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+');
1661 }
1662 $sink = $options['sink'];
1663 if (!\is_string($sink)) {
1664 $sink = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::streamFor($sink);
1665 } elseif (!\is_dir(\dirname($sink))) {
1666 // Ensure that the directory exists before failing in curl.
1667 throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink));
1668 } else {
1669 $sink = new \YoastSEO_Vendor\GuzzleHttp\Psr7\LazyOpenStream($sink, 'w+');
1670 }
1671 $easy->sink = $sink;
1672 $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use($sink) : int {
1673 return $sink->write($write);
1674 };
1675 $timeoutRequiresNoSignal = \false;
1676 if (isset($options['timeout'])) {
1677 $timeoutRequiresNoSignal |= $options['timeout'] < 1;
1678 $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
1679 }
1680 // CURL default value is CURL_IPRESOLVE_WHATEVER
1681 if (isset($options['force_ip_resolve'])) {
1682 if ('v4' === $options['force_ip_resolve']) {
1683 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4;
1684 } elseif ('v6' === $options['force_ip_resolve']) {
1685 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6;
1686 }
1687 }
1688 if (isset($options['connect_timeout'])) {
1689 $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1;
1690 $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
1691 }
1692 if ($timeoutRequiresNoSignal && \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToUpper(\substr(\PHP_OS, 0, 3)) !== 'WIN') {
1693 $conf[\CURLOPT_NOSIGNAL] = \true;
1694 }
1695 // Always pin CURLOPT_PROXY (and CURLOPT_NOPROXY when available) so
1696 // that libcurl never falls back to reading proxy environment
1697 // variables itself. When the proxy request option makes no decision,
1698 // the environment is resolved here with libcurl's own semantics.
1699 [$proxyConf, $noProxyConf] = self::resolveProxy($easy->request, $options);
1700 self::assertResolvedProxySupported($easy->request, $proxyConf);
1701 $conf[\CURLOPT_PROXY] = $proxyConf;
1702 if (\defined('CURLOPT_NOPROXY')) {
1703 $conf[(int) \constant('CURLOPT_NOPROXY')] = $noProxyConf;
1704 }
1705 $this->applyTlsVersionRange($easy, $conf);
1706 $certType = null;
1707 if (isset($options['cert_type'])) {
1708 $certType = self::normalizeTlsFileType('cert_type', $options['cert_type']);
1709 $conf[\CURLOPT_SSLCERTTYPE] = $certType;
1710 }
1711 if (isset($options['cert'])) {
1712 $cert = $options['cert'];
1713 if (\is_array($cert)) {
1714 if (!isset($cert[0]) || !\is_string($cert[0])) {
1715 throw new \InvalidArgumentException('Invalid cert request option');
1716 }
1717 if (isset($cert[1])) {
1718 if (!\is_string($cert[1])) {
1719 throw new \InvalidArgumentException('Invalid cert request option');
1720 }
1721 $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1];
1722 }
1723 $cert = $cert[0];
1724 }
1725 if (!\is_string($cert)) {
1726 throw new \InvalidArgumentException('Invalid cert request option');
1727 }
1728 if (!\file_exists($cert)) {
1729 throw new \InvalidArgumentException("SSL certificate not found: {$cert}");
1730 }
1731 // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
1732 // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
1733 $ext = \pathinfo($cert, \PATHINFO_EXTENSION);
1734 if ($certType === null && \preg_match('#^(der|p12)$#iD', $ext)) {
1735 $conf[\CURLOPT_SSLCERTTYPE] = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToUpper($ext);
1736 }
1737 $conf[\CURLOPT_SSLCERT] = $cert;
1738 }
1739 $sslKeyType = null;
1740 if (isset($options['ssl_key_type'])) {
1741 $sslKeyType = self::normalizeTlsFileType('ssl_key_type', $options['ssl_key_type']);
1742 $conf[\CURLOPT_SSLKEYTYPE] = $sslKeyType;
1743 }
1744 if (isset($options['ssl_key'])) {
1745 if (\is_array($options['ssl_key'])) {
1746 if (!isset($options['ssl_key'][0]) || !\is_string($options['ssl_key'][0])) {
1747 throw new \InvalidArgumentException('Invalid ssl_key request option');
1748 }
1749 if (isset($options['ssl_key'][1])) {
1750 if (!\is_string($options['ssl_key'][1])) {
1751 throw new \InvalidArgumentException('Invalid ssl_key request option');
1752 }
1753 $conf[\CURLOPT_SSLKEYPASSWD] = $options['ssl_key'][1];
1754 }
1755 $sslKey = $options['ssl_key'][0];
1756 }
1757 $sslKey = $sslKey ?? $options['ssl_key'];
1758 if (!\is_string($sslKey)) {
1759 throw new \InvalidArgumentException('Invalid ssl_key request option');
1760 }
1761 if (self::shouldValidateSslKeyFile($sslKeyType) && !\file_exists($sslKey)) {
1762 throw new \InvalidArgumentException("SSL private key not found: {$sslKey}");
1763 }
1764 $conf[\CURLOPT_SSLKEY] = $sslKey;
1765 }
1766 if (isset($options['progress'])) {
1767 $progress = $options['progress'];
1768 if (!\is_callable($progress)) {
1769 throw new \InvalidArgumentException('progress client option must be callable');
1770 }
1771 $conf[\CURLOPT_NOPROGRESS] = \false;
1772 $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use($progress) {
1773 $progress($downloadSize, $downloaded, $uploadSize, $uploaded);
1774 };
1775 }
1776 if (!empty($options['debug'])) {
1777 $conf[\CURLOPT_STDERR] = \YoastSEO_Vendor\GuzzleHttp\Utils::debugResource($options['debug']);
1778 $conf[\CURLOPT_VERBOSE] = \true;
1779 }
1780 }
1781 private function applyTlsVersionRange(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) : void
1782 {
1783 $options = $easy->options;
1784 $cryptoMethod = $options['crypto_method'] ?? null;
1785 $cryptoMethodMax = $options['crypto_method_max'] ?? null;
1786 if ($cryptoMethod === null && $cryptoMethodMax === null) {
1787 return;
1788 }
1789 $protocolVersion = $easy->request->getProtocolVersion();
1790 $isHttp2 = '2' === $protocolVersion || '2.0' === $protocolVersion;
1791 if ($isHttp2 && $cryptoMethodMax !== null && \YoastSEO_Vendor\GuzzleHttp\Handler\TlsVersion::ordinal('crypto_method_max', $cryptoMethodMax) < 12) {
1792 throw new \InvalidArgumentException('Invalid crypto_method_max request option: HTTP/2 requires TLS 1.2 or higher');
1793 }
1794 if ($isHttp2 && $cryptoMethod !== null && \YoastSEO_Vendor\GuzzleHttp\Handler\TlsVersion::ordinal('crypto_method', $cryptoMethod) < 12) {
1795 $cryptoMethod = \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
1796 }
1797 \YoastSEO_Vendor\GuzzleHttp\Handler\TlsVersion::assertRange($cryptoMethod, $cryptoMethodMax);
1798 $sslVersion = $cryptoMethod === null ? \CURL_SSLVERSION_DEFAULT : self::curlMinSslVersion($cryptoMethod);
1799 if ($cryptoMethodMax !== null) {
1800 $sslVersion |= self::curlMaxSslVersion($cryptoMethodMax);
1801 }
1802 $conf[\CURLOPT_SSLVERSION] = $sslVersion;
1803 }
1804 /**
1805 * @param mixed $value
1806 */
1807 private static function curlMinSslVersion($value) : int
1808 {
1809 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
1810 return \CURL_SSLVERSION_TLSv1_0;
1811 }
1812 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
1813 return \CURL_SSLVERSION_TLSv1_1;
1814 }
1815 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
1816 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsTls12()) {
1817 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL');
1818 }
1819 return \CURL_SSLVERSION_TLSv1_2;
1820 }
1821 if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
1822 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsTls13()) {
1823 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
1824 }
1825 return \CURL_SSLVERSION_TLSv1_3;
1826 }
1827 throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
1828 }
1829 /**
1830 * @param mixed $value
1831 */
1832 private static function curlMaxSslVersion($value) : int
1833 {
1834 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
1835 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_0');
1836 }
1837 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
1838 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_1');
1839 }
1840 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
1841 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_2');
1842 }
1843 if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
1844 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_3');
1845 }
1846 throw new \InvalidArgumentException('Invalid crypto_method_max request option: unknown version provided');
1847 }
1848 private static function requireCurlMaxSslVersion(string $constant) : int
1849 {
1850 if (\defined($constant)) {
1851 /** @var int */
1852 return \constant($constant);
1853 }
1854 throw new \InvalidArgumentException('Invalid crypto_method_max request option: maximum TLS version control is not supported by your version of cURL');
1855 }
1856 private static function validateRequestUriScheme(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request) : void
1857 {
1858 $scheme = $request->getUri()->getScheme();
1859 if ($scheme === '') {
1860 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request);
1861 }
1862 if (!\in_array($scheme, ['http', 'https'], \true)) {
1863 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
1864 }
1865 }
1866 /**
1867 * This function ensures that a response was set on a transaction. If one
1868 * was not set, then the request is retried if possible. This error
1869 * typically means you are sending a payload, curl encountered a
1870 * "Connection died, retrying a fresh connect" error, tried to rewind the
1871 * stream, and then encountered a "necessary data rewind wasn't possible"
1872 * error, causing the request to be sent through curl_multi_info_read()
1873 * without an error status.
1874 *
1875 * @param callable(RequestInterface, array): PromiseInterface $handler
1876 */
1877 private static function retryFailedRewind(callable $handler, \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array $ctx) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
1878 {
1879 try {
1880 // Only rewind if the body has been read from.
1881 $body = $easy->request->getBody();
1882 if ($body->tell() > 0) {
1883 $body->rewind();
1884 }
1885 } catch (\RuntimeException $e) {
1886 $ctx['error'] = 'The connection unexpectedly failed without ' . 'providing an error. The request would have been retried, ' . 'but attempting to rewind the request body failed. ' . 'Exception: ' . $e;
1887 return self::createRejection($easy, $ctx);
1888 }
1889 // Retry no more than 3 times before giving up.
1890 if (!isset($easy->options['_curl_retries'])) {
1891 $easy->options['_curl_retries'] = 1;
1892 } elseif ($easy->options['_curl_retries'] == 2) {
1893 $ctx['error'] = 'The cURL request was retried 3 times ' . 'and did not succeed. The most likely reason for the failure ' . 'is that cURL was unable to rewind the body of the request ' . 'and subsequent retries resulted in the same error. Turn on ' . 'the debug option to see what went wrong. See ' . 'https://bugs.php.net/bug.php?id=47204 for more information.';
1894 return self::createRejection($easy, $ctx);
1895 } else {
1896 ++$easy->options['_curl_retries'];
1897 }
1898 return $handler($easy->request, $easy->options);
1899 }
1900 /**
1901 * Parses validated trailer field lines into an associative array keyed by
1902 * lowercased field name, preserving first-occurrence key order and wire
1903 * value order.
1904 */
1905 private static function headersFromTrailerLines(array $lines) : array
1906 {
1907 $headers = [];
1908 foreach ($lines as $line) {
1909 [$name, $value] = \explode(':', $line, 2);
1910 $name = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToLower(\trim($name, " \n\r\t\x00\v"));
1911 $headers[$name][] = \trim($value, " \n\r\t\x00\v");
1912 }
1913 return $headers;
1914 }
1915 private function createHeaderFn(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : callable
1916 {
1917 if (isset($easy->options['on_headers'])) {
1918 $onHeaders = $easy->options['on_headers'];
1919 if (!\is_callable($onHeaders)) {
1920 throw new \InvalidArgumentException('on_headers must be callable');
1921 }
1922 } else {
1923 $onHeaders = null;
1924 }
1925 $startingResponse = \false;
1926 $collectingTrailers = \false;
1927 $retainTrailers = isset($easy->options['on_trailers']);
1928 return static function ($ch, $h) use($onHeaders, $easy, &$startingResponse, &$collectingTrailers, $retainTrailers) {
1929 $value = \trim($h, " \n\r\t\x00\v");
1930 if ($h === "\r\n" || $h === "\n" || $h === "\r" || $h === '') {
1931 if ($collectingTrailers) {
1932 // A blank line ends the trailer section; the response has
1933 // already been created.
1934 return \strlen($h);
1935 }
1936 $startingResponse = \true;
1937 try {
1938 $easy->createResponse();
1939 } catch (\Throwable $e) {
1940 $easy->response = null;
1941 $easy->createResponseException = $e;
1942 return -1;
1943 }
1944 if ($onHeaders !== null) {
1945 try {
1946 $onHeaders($easy->response);
1947 } catch (\Throwable $e) {
1948 // Associate the exception with the handle and trigger
1949 // a curl header write error by returning 0.
1950 $easy->onHeadersException = $e;
1951 return -1;
1952 }
1953 }
1954 } elseif ($startingResponse || $collectingTrailers) {
1955 if ($easy->response !== null && !\YoastSEO_Vendor\GuzzleHttp\Handler\HeaderProcessor::isStatusLineCandidate($h)) {
1956 // Trailer fields arrive through the header callback after
1957 // the body; a new header block always begins with a status
1958 // line.
1959 $collectingTrailers = \true;
1960 if ($retainTrailers && \YoastSEO_Vendor\GuzzleHttp\Handler\HeaderProcessor::isValidHeaderFieldLine($h)) {
1961 $easy->trailers[] = $value;
1962 }
1963 } else {
1964 $collectingTrailers = \false;
1965 $easy->trailers = [];
1966 $easy->headers = [$value];
1967 }
1968 $startingResponse = \false;
1969 } else {
1970 $easy->headers[] = $value;
1971 }
1972 return \strlen($h);
1973 };
1974 }
1975 public function __destruct()
1976 {
1977 $this->discardIdleHandles();
1978 }
1979 }
1980