PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.1
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.1
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.1, at vendor_prefixed/guzzlehttp/guzzle/src/Handler/CurlFactory.php

998 lines 52.5 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\Promise as P;
8 use YoastSEO_Vendor\GuzzleHttp\Promise\FulfilledPromise;
9 use YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface;
10 use YoastSEO_Vendor\GuzzleHttp\Psr7;
11 use YoastSEO_Vendor\GuzzleHttp\Psr7\LazyOpenStream;
12 use YoastSEO_Vendor\GuzzleHttp\Psr7\Uri;
13 use YoastSEO_Vendor\GuzzleHttp\TransferStats;
14 use YoastSEO_Vendor\GuzzleHttp\TransportSharing;
15 use YoastSEO_Vendor\GuzzleHttp\Utils;
16 use YoastSEO_Vendor\Psr\Http\Message\RequestInterface;
17 use YoastSEO_Vendor\Psr\Http\Message\UriInterface;
18 /**
19 * Creates curl resources from a request
20 *
21 * @final
22 */
23 class CurlFactory implements \YoastSEO_Vendor\GuzzleHttp\Handler\CurlFactoryInterface
24 {
25 public const CURL_VERSION_STR = 'curl_version';
26 /**
27 * @deprecated
28 */
29 public const LOW_CURL_VERSION_NUMBER = '7.21.2';
30 /**
31 * @var resource[]|\CurlHandle[]
32 */
33 private $handles = [];
34 /**
35 * @var int Total number of idle handles to keep in cache
36 */
37 private $maxHandles;
38 /**
39 * @var resource|\CurlShareHandle|null
40 */
41 private $shareHandle;
42 /**
43 * @var string
44 */
45 private $shareMode;
46 /**
47 * @param int $maxHandles Maximum number of idle handles.
48 * @param resource|\CurlShareHandle|null $shareHandle
49 */
50 public function __construct(int $maxHandles, string $shareMode = \YoastSEO_Vendor\GuzzleHttp\TransportSharing::NONE, $shareHandle = null)
51 {
52 $this->maxHandles = $maxHandles;
53 $this->shareMode = \YoastSEO_Vendor\GuzzleHttp\Handler\CurlShareHandleState::normalizeMode($shareMode, 'transport_sharing');
54 if ($this->shareMode === \YoastSEO_Vendor\GuzzleHttp\TransportSharing::NONE && $shareHandle !== null) {
55 throw new \InvalidArgumentException('A cURL share handle cannot be provided when transport sharing is disabled.');
56 }
57 if ($this->shareMode !== \YoastSEO_Vendor\GuzzleHttp\TransportSharing::NONE && $shareHandle === null) {
58 throw new \InvalidArgumentException('A cURL share handle is required when transport sharing is enabled.');
59 }
60 if ($shareHandle !== null && !self::isCurlShareHandle($shareHandle)) {
61 throw new \InvalidArgumentException('A cURL share handle must be an instance of CurlShareHandle or a curl_share resource.');
62 }
63 $this->shareHandle = $shareHandle;
64 }
65 /**
66 * @param mixed $value
67 */
68 private static function isCurlShareHandle($value) : bool
69 {
70 if (\PHP_VERSION_ID < 80000) {
71 return \is_resource($value) && \get_resource_type($value) === 'curl_share';
72 }
73 return $value instanceof \CurlShareHandle;
74 }
75 public function create(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $options) : \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle
76 {
77 $protocolVersion = $request->getProtocolVersion();
78 if ('' === $protocolVersion) {
79 \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.');
80 $protocolVersion = '1.1';
81 $request = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
82 }
83 if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
84 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsHttp2()) {
85 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException('HTTP/2 is supported by the cURL handler, however libcurl is built without HTTP/2 support.', $request);
86 }
87 } elseif ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
88 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\ConnectException(\sprintf('HTTP/%s is not supported by the cURL handler.', $protocolVersion), $request);
89 }
90 if (isset($options['curl']['body_as_string'])) {
91 $options['_body_as_string'] = $options['curl']['body_as_string'];
92 unset($options['curl']['body_as_string']);
93 }
94 self::triggerUnsupportedRequestOptionDeprecations($options);
95 $this->rejectRequestLevelShareConflict($options);
96 self::triggerUnsupportedCurlOptionDeprecations($options);
97 self::triggerConflictingCurlOptionDeprecations($options);
98 $easy = new \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle();
99 $easy->request = $request;
100 $easy->options = $options;
101 $conf = $this->getDefaultConf($easy);
102 $this->applyMethod($easy, $conf);
103 $this->applyHandlerOptions($easy, $conf);
104 $this->applyHeaders($easy, $conf);
105 unset($conf['_headers']);
106 // Add handler options from the request configuration options
107 if (isset($options['curl'])) {
108 $conf = \array_replace($conf, $options['curl']);
109 }
110 $easy->effectiveProxy = self::getEffectiveProxy($conf);
111 $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
112 if ($this->shareHandle !== null) {
113 if (!\defined('CURLOPT_SHARE')) {
114 throw new \InvalidArgumentException('The configured cURL share handle requires CURLOPT_SHARE, but it is not available in the installed PHP cURL extension.');
115 }
116 $conf[(int) \constant('CURLOPT_SHARE')] = $this->shareHandle;
117 }
118 $handle = $this->handles ? \array_pop($this->handles) : \curl_init();
119 if (\false === $handle) {
120 throw new \RuntimeException('Can not initialize cURL handle.');
121 }
122 $easy->handle = $handle;
123 try {
124 $this->applyCurlOptions($handle, $conf);
125 } catch (\Throwable $e) {
126 if (\PHP_VERSION_ID < 80000 && \is_resource($handle)) {
127 \curl_close($handle);
128 }
129 unset($easy->handle);
130 throw $e;
131 }
132 return $easy;
133 }
134 /**
135 * @param resource|\CurlHandle $handle
136 * @param array<int|string, mixed> $conf
137 */
138 private function applyCurlOptions($handle, array $conf) : void
139 {
140 foreach ($conf as $option => $value) {
141 if (!\is_int($option)) {
142 throw new \InvalidArgumentException(\sprintf('Invalid cURL option %s.', self::formatCurlOption($option)));
143 }
144 try {
145 $success = \curl_setopt($handle, $option, $value);
146 } catch (\Throwable $e) {
147 throw new \InvalidArgumentException(\sprintf('Unable to set cURL option %s: %s', self::formatCurlOption($option), $e->getMessage()), 0, $e);
148 }
149 if (!$success) {
150 throw new \InvalidArgumentException(\sprintf('Unable to set cURL option %s.', self::formatCurlOption($option)));
151 }
152 }
153 }
154 private function rejectRequestLevelShareConflict(array $options) : void
155 {
156 if ($this->shareHandle === null) {
157 return;
158 }
159 if (!\defined('CURLOPT_SHARE') || !isset($options['curl']) || !\is_array($options['curl']) || !\array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl'])) {
160 return;
161 }
162 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with configured transport sharing.');
163 }
164 /**
165 * @param int|string $option
166 */
167 private static function formatCurlOption($option) : string
168 {
169 if (!\is_int($option)) {
170 return \sprintf('"%s"', $option);
171 }
172 static $names = null;
173 if (null === $names) {
174 $names = [];
175 foreach (\get_defined_constants(\true)['curl'] ?? [] as $name => $value) {
176 if (\is_int($value) && \strpos($name, 'CURLOPT_') === 0 && !isset($names[$value])) {
177 $names[$value] = $name;
178 }
179 }
180 }
181 if (isset($names[$option])) {
182 return \sprintf('%s (%d)', $names[$option], $option);
183 }
184 return (string) $option;
185 }
186 private static function triggerConflictingCurlOptionDeprecations(array $options) : void
187 {
188 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
189 return;
190 }
191 $conflictingOptions = self::conflictingCurlOptions();
192 foreach ($options['curl'] as $option => $_) {
193 if (!\array_key_exists($option, $conflictingOptions)) {
194 continue;
195 }
196 $name = self::formatCurlOption($option);
197 $replacement = $conflictingOptions[$option];
198 if ($replacement !== null) {
199 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', '7.11', \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));
200 continue;
201 }
202 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/guzzle', '7.11', \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));
203 }
204 }
205 private static function triggerUnsupportedCurlOptionDeprecations(array $options) : void
206 {
207 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
208 return;
209 }
210 $supportedOptions = self::supportedCurlOptions();
211 $conflictingOptions = self::conflictingCurlOptions();
212 foreach ($options['curl'] as $option => $_) {
213 if (!\is_int($option) || \array_key_exists($option, $supportedOptions) || \array_key_exists($option, $conflictingOptions)) {
214 continue;
215 }
216 \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)));
217 }
218 }
219 private static function triggerUnsupportedRequestOptionDeprecations(array $options) : void
220 {
221 if (\array_key_exists('stream_context', $options)) {
222 \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.');
223 }
224 }
225 /**
226 * @return array<int, string|null>
227 */
228 private static function conflictingCurlOptions() : array
229 {
230 static $options = null;
231 if ($options !== null) {
232 return $options;
233 }
234 $options = [];
235 self::addConflictingCurlOption($options, 'CURLOPT_SHARE', 'the "transport_sharing" client option or cURL handler option');
236 self::addConflictingCurlOption($options, 'CURLOPT_URL', 'the request URI');
237 self::addConflictingCurlOption($options, 'CURLOPT_PORT', 'the request URI');
238 self::addConflictingCurlOption($options, 'CURLOPT_CUSTOMREQUEST', 'the request method');
239 self::addConflictingCurlOption($options, 'CURLOPT_HTTPGET', 'the request method');
240 self::addConflictingCurlOption($options, 'CURLOPT_POST', 'the request method and body');
241 self::addConflictingCurlOption($options, 'CURLOPT_PUT', 'the request method and body');
242 self::addConflictingCurlOption($options, 'CURLOPT_NOBODY', 'the request method');
243 self::addConflictingCurlOption($options, 'CURLOPT_UPLOAD', 'the request body');
244 self::addConflictingCurlOption($options, 'CURLOPT_POSTFIELDS', 'the request body');
245 self::addConflictingCurlOption($options, 'CURLOPT_READFUNCTION', 'the request body');
246 self::addConflictingCurlOption($options, 'CURLOPT_READDATA', 'the request body');
247 self::addConflictingCurlOption($options, 'CURLOPT_INFILE', 'the request body');
248 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE', 'the request body');
249 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE_LARGE', 'the request body');
250 self::addConflictingCurlOption($options, 'CURLOPT_HTTPHEADER', 'the request headers');
251 self::addConflictingCurlOption($options, 'CURLOPT_USERAGENT', 'the request headers');
252 self::addConflictingCurlOption($options, 'CURLOPT_REFERER', 'the request headers');
253 self::addConflictingCurlOption($options, 'CURLOPT_HEADERFUNCTION', 'the "on_headers" request option');
254 self::addConflictingCurlOption($options, 'CURLOPT_WRITEFUNCTION', 'the "sink" request option');
255 self::addConflictingCurlOption($options, 'CURLOPT_FILE', 'the "sink" request option');
256 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT', 'the "timeout" request option');
257 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT_MS', 'the "timeout" request option');
258 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT', 'the "connect_timeout" request option');
259 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT_MS', 'the "connect_timeout" request option');
260 self::addConflictingCurlOption($options, 'CURLOPT_NOSIGNAL', 'the "timeout" or "connect_timeout" request option');
261 self::addConflictingCurlOption($options, 'CURLOPT_NOPROGRESS', 'the "progress" request option');
262 self::addConflictingCurlOption($options, 'CURLOPT_PROGRESSFUNCTION', 'the "progress" request option');
263 self::addConflictingCurlOption($options, 'CURLOPT_XFERINFOFUNCTION', 'the "progress" request option');
264 self::addConflictingCurlOption($options, 'CURLOPT_VERBOSE', 'the "debug" request option');
265 self::addConflictingCurlOption($options, 'CURLOPT_STDERR', 'the "debug" request option');
266 self::addConflictingCurlOption($options, 'CURLOPT_PROXY', 'the "proxy" request option');
267 self::addConflictingCurlOption($options, 'CURLOPT_NOPROXY', 'the "proxy" request option');
268 self::addConflictingCurlOption($options, 'CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option');
269 self::addConflictingCurlOption($options, 'CURLOPT_MAXREDIRS', 'the "allow_redirects" request option');
270 self::addConflictingCurlOption($options, 'CURLOPT_POSTREDIR', 'the "allow_redirects" request option');
271 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS', 'the "allow_redirects" request option');
272 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS_STR', 'the "allow_redirects" request option');
273 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS', 'the "protocols" request option');
274 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS_STR', 'the "protocols" request option');
275 self::addConflictingCurlOption($options, 'CURLOPT_HTTP_VERSION', 'the request protocol version');
276 self::addConflictingCurlOption($options, 'CURLOPT_IPRESOLVE', 'the "force_ip_resolve" request option');
277 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYPEER', 'the "verify" request option');
278 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYHOST', 'the "verify" request option');
279 self::addConflictingCurlOption($options, 'CURLOPT_CAINFO', 'the "verify" request option');
280 self::addConflictingCurlOption($options, 'CURLOPT_CAPATH', 'the "verify" request option');
281 self::addConflictingCurlOption($options, 'CURLOPT_SSLVERSION', 'the "crypto_method" request option');
282 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERT', 'the "cert" request option');
283 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTPASSWD', 'the "cert" request option');
284 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTTYPE', 'the "cert_type" request option');
285 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEY', 'the "ssl_key" request option');
286 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYPASSWD', 'the "ssl_key" request option');
287 self::addConflictingCurlOption($options, 'CURLOPT_KEYPASSWD', 'the "ssl_key" request option');
288 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYTYPE', 'the "ssl_key_type" request option');
289 self::addConflictingCurlOption($options, 'CURLOPT_COOKIE', 'the "Cookie" request header or Guzzle cookie middleware');
290 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEFILE', 'Guzzle cookie middleware');
291 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEJAR', 'Guzzle cookie middleware');
292 self::addConflictingCurlOption($options, 'CURLOPT_COOKIELIST', 'Guzzle cookie middleware');
293 self::addConflictingCurlOption($options, 'CURLOPT_COOKIESESSION', 'Guzzle cookie middleware');
294 return $options;
295 }
296 /**
297 * @return array<int, true>
298 */
299 private static function supportedCurlOptions() : array
300 {
301 static $options = null;
302 if ($options !== null) {
303 return $options;
304 }
305 $options = [];
306 self::addSupportedCurlOption($options, 'CURLOPT_ADDRESS_SCOPE');
307 self::addSupportedCurlOption($options, 'CURLOPT_CONNECT_TO');
308 self::addSupportedCurlOption($options, 'CURLOPT_DNS_CACHE_TIMEOUT');
309 self::addSupportedCurlOption($options, 'CURLOPT_DNS_INTERFACE');
310 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP4');
311 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP6');
312 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SERVERS');
313 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SHUFFLE_ADDRESSES');
314 self::addSupportedCurlOption($options, 'CURLOPT_ENCODING');
315 self::addSupportedCurlOption($options, 'CURLOPT_FORBID_REUSE');
316 self::addSupportedCurlOption($options, 'CURLOPT_FRESH_CONNECT');
317 self::addSupportedCurlOption($options, 'CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS');
318 self::addSupportedCurlOption($options, 'CURLOPT_HTTPAUTH');
319 self::addSupportedCurlOption($options, 'CURLOPT_INTERFACE');
320 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORT');
321 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORTRANGE');
322 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_LIMIT');
323 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_TIME');
324 self::addSupportedCurlOption($options, 'CURLOPT_MAXAGE_CONN');
325 self::addSupportedCurlOption($options, 'CURLOPT_MAXCONNECTS');
326 self::addSupportedCurlOption($options, 'CURLOPT_MAXLIFETIME_CONN');
327 self::addSupportedCurlOption($options, 'CURLOPT_HTTPPROXYTUNNEL');
328 self::addSupportedCurlOption($options, 'CURLOPT_PROXYHEADER');
329 self::addSupportedCurlOption($options, 'CURLOPT_PROXYUSERPWD');
330 self::addSupportedCurlOption($options, 'CURLOPT_RESOLVE');
331 self::addSupportedCurlOption($options, 'CURLOPT_SSL_CIPHER_LIST');
332 self::addSupportedCurlOption($options, 'CURLOPT_SSL_EC_CURVES');
333 self::addSupportedCurlOption($options, 'CURLOPT_TCP_FASTOPEN');
334 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPALIVE');
335 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPIDLE');
336 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPINTVL');
337 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPCNT');
338 self::addSupportedCurlOption($options, 'CURLOPT_TCP_NODELAY');
339 self::addSupportedCurlOption($options, 'CURLOPT_TLS13_CIPHERS');
340 self::addSupportedCurlOption($options, 'CURLOPT_UNIX_SOCKET_PATH');
341 self::addSupportedCurlOption($options, 'CURLOPT_USERPWD');
342 return $options;
343 }
344 /**
345 * @param array<int, true> $options
346 */
347 private static function addSupportedCurlOption(array &$options, string $constant) : void
348 {
349 if (!\defined($constant)) {
350 return;
351 }
352 $value = \constant($constant);
353 if (\is_int($value)) {
354 $options[$value] = \true;
355 }
356 }
357 /**
358 * @param array<int, string|null> $options
359 */
360 private static function addConflictingCurlOption(array &$options, string $constant, ?string $replacement) : void
361 {
362 if (!\defined($constant)) {
363 return;
364 }
365 $value = \constant($constant);
366 if (\is_int($value)) {
367 $options[$value] = $replacement;
368 }
369 }
370 public function release(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : void
371 {
372 $resource = $easy->handle;
373 unset($easy->handle);
374 if (\count($this->handles) >= $this->maxHandles) {
375 if (\PHP_VERSION_ID < 80000) {
376 \curl_close($resource);
377 }
378 } else {
379 // Remove all callback functions as they can hold onto references
380 // and are not cleaned up by curl_reset. Using curl_setopt_array
381 // does not work for some reason, so removing each one
382 // individually.
383 \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null);
384 \curl_setopt($resource, \CURLOPT_READFUNCTION, null);
385 \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null);
386 \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null);
387 \curl_reset($resource);
388 $this->handles[] = $resource;
389 }
390 }
391 /**
392 * Completes a cURL transaction, either returning a response promise or a
393 * rejected promise.
394 *
395 * @param callable(RequestInterface, array): PromiseInterface $handler
396 * @param CurlFactoryInterface $factory Dictates how the handle is released
397 */
398 public static function finish(callable $handler, \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, \YoastSEO_Vendor\GuzzleHttp\Handler\CurlFactoryInterface $factory) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
399 {
400 if (isset($easy->options['on_stats'])) {
401 self::invokeStats($easy);
402 }
403 if (!$easy->response || $easy->errno) {
404 return self::finishError($handler, $easy, $factory);
405 }
406 // Return the response if it is present and there is no error.
407 $factory->release($easy);
408 // Rewind the body of the response if possible.
409 $body = $easy->response->getBody();
410 if ($body->isSeekable()) {
411 $body->rewind();
412 }
413 return new \YoastSEO_Vendor\GuzzleHttp\Promise\FulfilledPromise($easy->response);
414 }
415 private static function invokeStats(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : void
416 {
417 $curlStats = \curl_getinfo($easy->handle);
418 $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME);
419 $stats = new \YoastSEO_Vendor\GuzzleHttp\TransferStats($easy->request, $easy->response, $curlStats['total_time'], $easy->errno, $curlStats);
420 $easy->options['on_stats']($stats);
421 }
422 /**
423 * @param callable(RequestInterface, array): PromiseInterface $handler
424 */
425 private static function finishError(callable $handler, \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, \YoastSEO_Vendor\GuzzleHttp\Handler\CurlFactoryInterface $factory) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
426 {
427 // Get error information and release the handle to the factory.
428 $ctx = ['errno' => $easy->errno, 'error' => \curl_error($easy->handle), 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME)] + \curl_getinfo($easy->handle);
429 $ctx[self::CURL_VERSION_STR] = \YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::getVersion() ?? '';
430 $factory->release($easy);
431 // Retry when nothing is present or when curl failed to rewind.
432 if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) {
433 return self::retryFailedRewind($handler, $easy, $ctx);
434 }
435 return self::createRejection($easy, $ctx);
436 }
437 private static function createRejection(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array $ctx) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
438 {
439 static $connectionErrors = [\CURLE_OPERATION_TIMEOUTED => \true, \CURLE_COULDNT_RESOLVE_HOST => \true, \CURLE_COULDNT_CONNECT => \true, \CURLE_SSL_CONNECT_ERROR => \true, \CURLE_GOT_NOTHING => \true];
440 if ($easy->createResponseException) {
441 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));
442 }
443 // If an exception was encountered during the onHeaders event, then
444 // return a rejected promise that wraps that exception.
445 if ($easy->onHeadersException) {
446 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));
447 }
448 $uri = $easy->request->getUri();
449 $sanitizedError = self::sanitizeCurlError($ctx['error'] ?? '', $uri, $easy->effectiveProxy);
450 $message = \sprintf('cURL error %s: %s (%s)', $ctx['errno'], $sanitizedError, 'see https://curl.se/libcurl/c/libcurl-errors.html');
451 if ('' !== $sanitizedError) {
452 $redactedUriString = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::redactUserInfo($uri)->__toString();
453 if ($redactedUriString !== '' && \false === \strpos($sanitizedError, $redactedUriString)) {
454 $message .= \sprintf(' for %s', $redactedUriString);
455 }
456 }
457 // Create a connection exception if it was a specific error code.
458 $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);
459 return \YoastSEO_Vendor\GuzzleHttp\Promise\Create::rejectionFor($error);
460 }
461 private static function sanitizeCurlError(string $error, \YoastSEO_Vendor\Psr\Http\Message\UriInterface $uri, ?string $proxy = null) : string
462 {
463 if ('' === $error) {
464 return $error;
465 }
466 $error = self::redactProxyUserInfo($error, $proxy);
467 $baseUri = $uri->withQuery('')->withFragment('');
468 $baseUriString = $baseUri->__toString();
469 if ('' === $baseUriString) {
470 return $error;
471 }
472 $redactedUriString = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::redactUserInfo($baseUri)->__toString();
473 return \str_replace($baseUriString, $redactedUriString, $error);
474 }
475 private static function redactProxyUserInfo(string $error, ?string $proxy) : string
476 {
477 if ($proxy === null || $proxy === '' || \strpos($proxy, '@') === \false) {
478 return $error;
479 }
480 // The error message embeds the proxy string exactly as configured,
481 // so the userinfo needle is extracted with parse_url(): Psr7\Uri
482 // normalizes the components, which could make the replacement miss.
483 $proxyForParsing = \strpos($proxy, '://') === \false ? 'http://' . $proxy : $proxy;
484 $proxyParts = \parse_url($proxyForParsing);
485 if (!\is_array($proxyParts)) {
486 // Proxy strings that defeat parse_url() are exactly the ones
487 // libcurl embeds verbatim in error text such as "Unsupported
488 // proxy syntax in '...'": redact everything up to the last '@'
489 // of the authority as a safe-side fallback.
490 $authority = \substr($proxyForParsing, \strpos($proxyForParsing, '://') + 3);
491 $atPosition = \strrpos($authority, '@');
492 if ($atPosition === \false || $atPosition === 0) {
493 return $error;
494 }
495 return \str_replace(\substr($authority, 0, $atPosition) . '@', '***@', $error);
496 }
497 if (!isset($proxyParts['user']) && !isset($proxyParts['pass'])) {
498 return $error;
499 }
500 $userInfo = $proxyParts['user'] ?? '';
501 if (isset($proxyParts['pass'])) {
502 $userInfo .= ':' . $proxyParts['pass'];
503 }
504 if ($userInfo === '') {
505 return $error;
506 }
507 $redactedUserInfo = '***';
508 try {
509 $proxyUri = new \YoastSEO_Vendor\GuzzleHttp\Psr7\Uri($proxyForParsing);
510 $redactedUserInfo = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::redactUserInfo($proxyUri)->getUserInfo();
511 if ($redactedUserInfo === $proxyUri->getUserInfo()) {
512 return $error;
513 }
514 } catch (\InvalidArgumentException $e) {
515 // Unparseable as a URI: fall back to redacting the whole userinfo.
516 }
517 return \str_replace($userInfo . '@', $redactedUserInfo . '@', $error);
518 }
519 /**
520 * @param array<int|string, mixed> $conf
521 */
522 private static function getEffectiveProxy(array $conf) : ?string
523 {
524 if (!\array_key_exists(\CURLOPT_PROXY, $conf)) {
525 return null;
526 }
527 $proxy = $conf[\CURLOPT_PROXY];
528 return \is_string($proxy) && $proxy !== '' ? $proxy : null;
529 }
530 private static function proxyScheme(string $proxy) : ?string
531 {
532 $position = \strpos($proxy, '://');
533 return $position === \false ? null : \strtolower(\substr($proxy, 0, $position));
534 }
535 /**
536 * @return array<int|string, mixed>
537 */
538 private function getDefaultConf(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : array
539 {
540 $conf = ['_headers' => $easy->request->getHeaders(), \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), \CURLOPT_RETURNTRANSFER => \false, \CURLOPT_HEADER => \false, \CURLOPT_CONNECTTIMEOUT => 300];
541 $protocols = \YoastSEO_Vendor\GuzzleHttp\Utils::normalizeProtocols($easy->options['protocols'] ?? ['http', 'https']);
542 $scheme = $easy->request->getUri()->getScheme();
543 if (!\in_array($scheme, $protocols, \true)) {
544 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $easy->request);
545 }
546 if (\defined('CURLOPT_PROTOCOLS')) {
547 $conf[\CURLOPT_PROTOCOLS] = self::curlProtocolMask($protocols);
548 }
549 $version = $easy->request->getProtocolVersion();
550 if ('2' === $version || '2.0' === $version) {
551 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
552 } elseif ('1.1' === $version) {
553 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
554 } else {
555 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
556 }
557 return $conf;
558 }
559 /**
560 * @param string[] $protocols
561 */
562 private static function curlProtocolMask(array $protocols) : int
563 {
564 $mask = 0;
565 if (\in_array('http', $protocols, \true)) {
566 $mask |= \CURLPROTO_HTTP;
567 }
568 if (\in_array('https', $protocols, \true)) {
569 $mask |= \CURLPROTO_HTTPS;
570 }
571 return $mask;
572 }
573 /**
574 * @param mixed $type
575 */
576 private static function normalizeTlsFileType(string $option, $type) : string
577 {
578 if (!\is_string($type) || $type === '') {
579 throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
580 }
581 return \strtoupper($type);
582 }
583 private static function shouldValidateSslKeyFile(?string $type) : bool
584 {
585 return $type !== 'ENG' && $type !== 'PROV';
586 }
587 private function applyMethod(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) : void
588 {
589 $body = $easy->request->getBody();
590 $size = $body->getSize();
591 if ($size === null || $size > 0) {
592 $this->applyBody($easy->request, $easy->options, $conf);
593 return;
594 }
595 $method = $easy->request->getMethod();
596 if ($method === 'PUT' || $method === 'POST') {
597 // See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
598 if (!$easy->request->hasHeader('Content-Length')) {
599 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
600 }
601 } elseif ($method === 'HEAD') {
602 $conf[\CURLOPT_NOBODY] = \true;
603 unset($conf[\CURLOPT_WRITEFUNCTION], $conf[\CURLOPT_READFUNCTION], $conf[\CURLOPT_FILE], $conf[\CURLOPT_INFILE]);
604 }
605 }
606 private function applyBody(\YoastSEO_Vendor\Psr\Http\Message\RequestInterface $request, array $options, array &$conf) : void
607 {
608 $size = $request->hasHeader('Content-Length') ? (int) $request->getHeaderLine('Content-Length') : null;
609 // Send the body as a string if the size is less than 1MB OR if the
610 // [curl][body_as_string] request value is set.
611 if ($size !== null && $size < 1000000 || !empty($options['_body_as_string'])) {
612 $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody();
613 // Don't duplicate the Content-Length header
614 $this->removeHeader('Content-Length', $conf);
615 $this->removeHeader('Transfer-Encoding', $conf);
616 } else {
617 $conf[\CURLOPT_UPLOAD] = \true;
618 if ($size !== null) {
619 $conf[\CURLOPT_INFILESIZE] = $size;
620 $this->removeHeader('Content-Length', $conf);
621 }
622 $body = $request->getBody();
623 if ($body->isSeekable()) {
624 $body->rewind();
625 }
626 $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use($body) {
627 return $body->read($length);
628 };
629 }
630 // If the Expect header is not present, prevent curl from adding it
631 if (!$request->hasHeader('Expect')) {
632 $conf[\CURLOPT_HTTPHEADER][] = 'Expect:';
633 }
634 // cURL sometimes adds a content-type by default. Prevent this.
635 if (!$request->hasHeader('Content-Type')) {
636 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:';
637 }
638 }
639 private function applyHeaders(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) : void
640 {
641 foreach ($conf['_headers'] as $name => $values) {
642 foreach ($values as $value) {
643 $value = (string) $value;
644 if ($value === '') {
645 // cURL requires a special format for empty headers.
646 // See https://github.com/guzzle/guzzle/issues/1882 for more details.
647 $conf[\CURLOPT_HTTPHEADER][] = "{$name};";
648 } else {
649 $conf[\CURLOPT_HTTPHEADER][] = "{$name}: {$value}";
650 }
651 }
652 }
653 // Remove the Accept header if one was not set
654 if (!$easy->request->hasHeader('Accept')) {
655 $conf[\CURLOPT_HTTPHEADER][] = 'Accept:';
656 }
657 }
658 /**
659 * Remove a header from the options array.
660 *
661 * @param string $name Case-insensitive header to remove
662 * @param array $options Array of options to modify
663 */
664 private function removeHeader(string $name, array &$options) : void
665 {
666 foreach (\array_keys($options['_headers']) as $key) {
667 if (!\strcasecmp((string) $key, $name)) {
668 unset($options['_headers'][$key]);
669 return;
670 }
671 }
672 }
673 private function applyHandlerOptions(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array &$conf) : void
674 {
675 $options = $easy->options;
676 if (isset($options['verify'])) {
677 if ($options['verify'] === \false) {
678 unset($conf[\CURLOPT_CAINFO]);
679 $conf[\CURLOPT_SSL_VERIFYHOST] = 0;
680 $conf[\CURLOPT_SSL_VERIFYPEER] = \false;
681 } else {
682 $conf[\CURLOPT_SSL_VERIFYHOST] = 2;
683 $conf[\CURLOPT_SSL_VERIFYPEER] = \true;
684 if (\is_string($options['verify'])) {
685 // Throw an error if the file/folder/link path is not valid or doesn't exist.
686 if (!\file_exists($options['verify'])) {
687 throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}");
688 }
689 // If it's a directory or a link to a directory use CURLOPT_CAPATH.
690 // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO.
691 if (\is_dir($options['verify']) || \is_link($options['verify']) === \true && ($verifyLink = \readlink($options['verify'])) !== \false && \is_dir($verifyLink)) {
692 $conf[\CURLOPT_CAPATH] = $options['verify'];
693 } else {
694 $conf[\CURLOPT_CAINFO] = $options['verify'];
695 }
696 }
697 }
698 }
699 if (!isset($options['curl'][\CURLOPT_ENCODING]) && !empty($options['decode_content'])) {
700 $accept = $easy->request->getHeaderLine('Accept-Encoding');
701 if ($accept) {
702 $conf[\CURLOPT_ENCODING] = $accept;
703 } else {
704 // The empty string enables all available decoders and implicitly
705 // sets a matching 'Accept-Encoding' header.
706 $conf[\CURLOPT_ENCODING] = '';
707 // But as the user did not specify any encoding preference,
708 // let's leave it up to server by preventing curl from sending
709 // the header, which will be interpreted as 'Accept-Encoding: *'.
710 // https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
711 $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
712 }
713 }
714 if (!isset($options['sink'])) {
715 // Use a default temp stream if no sink was set.
716 $options['sink'] = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+');
717 }
718 $sink = $options['sink'];
719 if (!\is_string($sink)) {
720 $sink = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::streamFor($sink);
721 } elseif (!\is_dir(\dirname($sink))) {
722 // Ensure that the directory exists before failing in curl.
723 throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink));
724 } else {
725 $sink = new \YoastSEO_Vendor\GuzzleHttp\Psr7\LazyOpenStream($sink, 'w+');
726 }
727 $easy->sink = $sink;
728 $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use($sink) : int {
729 return $sink->write($write);
730 };
731 $timeoutRequiresNoSignal = \false;
732 if (isset($options['timeout'])) {
733 $timeoutRequiresNoSignal |= $options['timeout'] < 1;
734 $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
735 }
736 // CURL default value is CURL_IPRESOLVE_WHATEVER
737 if (isset($options['force_ip_resolve'])) {
738 if ('v4' === $options['force_ip_resolve']) {
739 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4;
740 } elseif ('v6' === $options['force_ip_resolve']) {
741 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6;
742 }
743 }
744 if (isset($options['connect_timeout'])) {
745 $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1;
746 $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
747 }
748 if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') {
749 $conf[\CURLOPT_NOSIGNAL] = \true;
750 }
751 // Always pin CURLOPT_PROXY (and CURLOPT_NOPROXY when available) so
752 // that libcurl never falls back to reading proxy environment
753 // variables itself. When the proxy request option makes no decision,
754 // the environment is resolved here with libcurl's own semantics.
755 $proxyConf = null;
756 $noProxyConf = '';
757 if (isset($options['proxy'])) {
758 if (!\is_array($options['proxy'])) {
759 $proxyConf = $options['proxy'];
760 } else {
761 $scheme = $easy->request->getUri()->getScheme();
762 if (isset($options['proxy'][$scheme])) {
763 if (isset($options['proxy']['no']) && \YoastSEO_Vendor\GuzzleHttp\Utils::isUriInNoProxy($easy->request->getUri(), $options['proxy']['no'])) {
764 $proxyConf = '';
765 $noProxyConf = '*';
766 } else {
767 $proxyConf = $options['proxy'][$scheme];
768 }
769 }
770 }
771 }
772 if ($proxyConf === null) {
773 $proxyConf = \YoastSEO_Vendor\GuzzleHttp\Handler\ProxyEnvironment::getProxyForScheme($easy->request->getUri()->getScheme());
774 if ($proxyConf === null) {
775 $proxyConf = '';
776 } elseif (($noProxy = \YoastSEO_Vendor\GuzzleHttp\Handler\ProxyEnvironment::getNoProxy()) !== null && \YoastSEO_Vendor\GuzzleHttp\Utils::isUriInNoProxy($easy->request->getUri(), \YoastSEO_Vendor\GuzzleHttp\Handler\ProxyEnvironment::splitNoProxy($noProxy))) {
777 // The environment no_proxy list is tokenized the way libcurl
778 // tokenizes it and matched here with the same rules as the
779 // proxy option's "no" list, so behavior does not depend on
780 // the installed libcurl's matcher.
781 $proxyConf = '';
782 $noProxyConf = '*';
783 }
784 }
785 if (\is_string($proxyConf) && $proxyConf !== '') {
786 $scheme = self::proxyScheme($proxyConf);
787 if ($scheme !== null && \preg_match('/^[a-z][a-z0-9.+-]*$/D', $scheme) !== 1) {
788 // A "://" with a prefix that is not a valid scheme (leading
789 // junk such as a space or non-breaking space) is treated by
790 // libcurl as an unknown scheme and silently downgraded to a
791 // plaintext HTTP proxy. Fail closed before any bytes reach the
792 // wire.
793 throw new \YoastSEO_Vendor\GuzzleHttp\Exception\RequestException('The proxy URL is malformed.', $easy->request);
794 }
795 if ($scheme === 'https' && !\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsHttpsProxy()) {
796 // libcurl before 7.50.2 silently downgrades an https:// proxy
797 // to a plaintext HTTP proxy; 7.50.2 through 7.51, and builds
798 // without HTTPS-proxy support, fail at connect time. Fail
799 // closed before any bytes reach the wire.
800 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.', $easy->request);
801 }
802 }
803 $conf[\CURLOPT_PROXY] = $proxyConf;
804 if (\defined('CURLOPT_NOPROXY')) {
805 $conf[(int) \constant('CURLOPT_NOPROXY')] = $noProxyConf;
806 }
807 if (isset($options['crypto_method'])) {
808 $protocolVersion = $easy->request->getProtocolVersion();
809 // If HTTP/2, upgrade TLS 1.0 and 1.1 to 1.2
810 if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
811 if (\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method'] || \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method'] || \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']) {
812 $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2;
813 } elseif (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) {
814 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsTls13()) {
815 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
816 }
817 $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3;
818 } else {
819 throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
820 }
821 } elseif (\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method']) {
822 $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_0;
823 } elseif (\STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method']) {
824 $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_1;
825 } elseif (\STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']) {
826 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsTls12()) {
827 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL');
828 }
829 $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2;
830 } elseif (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) {
831 if (!\YoastSEO_Vendor\GuzzleHttp\Handler\CurlVersion::supportsTls13()) {
832 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
833 }
834 $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3;
835 } else {
836 throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
837 }
838 }
839 $certType = null;
840 if (isset($options['cert_type'])) {
841 $certType = self::normalizeTlsFileType('cert_type', $options['cert_type']);
842 $conf[\CURLOPT_SSLCERTTYPE] = $certType;
843 }
844 if (isset($options['cert'])) {
845 $cert = $options['cert'];
846 if (\is_array($cert)) {
847 if (!isset($cert[0]) || !\is_string($cert[0])) {
848 throw new \InvalidArgumentException('Invalid cert request option');
849 }
850 if (isset($cert[1])) {
851 if (!\is_string($cert[1])) {
852 throw new \InvalidArgumentException('Invalid cert request option');
853 }
854 $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1];
855 }
856 $cert = $cert[0];
857 }
858 if (!\is_string($cert)) {
859 throw new \InvalidArgumentException('Invalid cert request option');
860 }
861 if (!\file_exists($cert)) {
862 throw new \InvalidArgumentException("SSL certificate not found: {$cert}");
863 }
864 // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
865 // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
866 $ext = \pathinfo($cert, \PATHINFO_EXTENSION);
867 if ($certType === null && \preg_match('#^(der|p12)$#i', $ext)) {
868 $conf[\CURLOPT_SSLCERTTYPE] = \strtoupper($ext);
869 }
870 $conf[\CURLOPT_SSLCERT] = $cert;
871 }
872 $sslKeyType = null;
873 if (isset($options['ssl_key_type'])) {
874 $sslKeyType = self::normalizeTlsFileType('ssl_key_type', $options['ssl_key_type']);
875 $conf[\CURLOPT_SSLKEYTYPE] = $sslKeyType;
876 }
877 if (isset($options['ssl_key'])) {
878 if (\is_array($options['ssl_key'])) {
879 if (!isset($options['ssl_key'][0]) || !\is_string($options['ssl_key'][0])) {
880 throw new \InvalidArgumentException('Invalid ssl_key request option');
881 }
882 if (isset($options['ssl_key'][1])) {
883 if (!\is_string($options['ssl_key'][1])) {
884 throw new \InvalidArgumentException('Invalid ssl_key request option');
885 }
886 $conf[\CURLOPT_SSLKEYPASSWD] = $options['ssl_key'][1];
887 }
888 $sslKey = $options['ssl_key'][0];
889 }
890 $sslKey = $sslKey ?? $options['ssl_key'];
891 if (!\is_string($sslKey)) {
892 throw new \InvalidArgumentException('Invalid ssl_key request option');
893 }
894 if (self::shouldValidateSslKeyFile($sslKeyType) && !\file_exists($sslKey)) {
895 throw new \InvalidArgumentException("SSL private key not found: {$sslKey}");
896 }
897 $conf[\CURLOPT_SSLKEY] = $sslKey;
898 }
899 if (isset($options['progress'])) {
900 $progress = $options['progress'];
901 if (!\is_callable($progress)) {
902 throw new \InvalidArgumentException('progress client option must be callable');
903 }
904 $conf[\CURLOPT_NOPROGRESS] = \false;
905 $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use($progress) {
906 $progress($downloadSize, $downloaded, $uploadSize, $uploaded);
907 };
908 }
909 if (!empty($options['debug'])) {
910 $conf[\CURLOPT_STDERR] = \YoastSEO_Vendor\GuzzleHttp\Utils::debugResource($options['debug']);
911 $conf[\CURLOPT_VERBOSE] = \true;
912 }
913 }
914 /**
915 * This function ensures that a response was set on a transaction. If one
916 * was not set, then the request is retried if possible. This error
917 * typically means you are sending a payload, curl encountered a
918 * "Connection died, retrying a fresh connect" error, tried to rewind the
919 * stream, and then encountered a "necessary data rewind wasn't possible"
920 * error, causing the request to be sent through curl_multi_info_read()
921 * without an error status.
922 *
923 * @param callable(RequestInterface, array): PromiseInterface $handler
924 */
925 private static function retryFailedRewind(callable $handler, \YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy, array $ctx) : \YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface
926 {
927 try {
928 // Only rewind if the body has been read from.
929 $body = $easy->request->getBody();
930 if ($body->tell() > 0) {
931 $body->rewind();
932 }
933 } catch (\RuntimeException $e) {
934 $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;
935 return self::createRejection($easy, $ctx);
936 }
937 // Retry no more than 3 times before giving up.
938 if (!isset($easy->options['_curl_retries'])) {
939 $easy->options['_curl_retries'] = 1;
940 } elseif ($easy->options['_curl_retries'] == 2) {
941 $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.';
942 return self::createRejection($easy, $ctx);
943 } else {
944 ++$easy->options['_curl_retries'];
945 }
946 return $handler($easy->request, $easy->options);
947 }
948 private function createHeaderFn(\YoastSEO_Vendor\GuzzleHttp\Handler\EasyHandle $easy) : callable
949 {
950 if (isset($easy->options['on_headers'])) {
951 $onHeaders = $easy->options['on_headers'];
952 if (!\is_callable($onHeaders)) {
953 throw new \InvalidArgumentException('on_headers must be callable');
954 }
955 } else {
956 $onHeaders = null;
957 }
958 return static function ($ch, $h) use($onHeaders, $easy, &$startingResponse) {
959 $value = \trim($h);
960 if ($value === '') {
961 $startingResponse = \true;
962 try {
963 $easy->createResponse();
964 } catch (\Throwable $e) {
965 $easy->response = null;
966 $easy->createResponseException = $e;
967 return -1;
968 }
969 if ($onHeaders !== null) {
970 try {
971 $onHeaders($easy->response);
972 } catch (\Throwable $e) {
973 // Associate the exception with the handle and trigger
974 // a curl header write error by returning 0.
975 $easy->onHeadersException = $e;
976 return -1;
977 }
978 }
979 } elseif ($startingResponse) {
980 $startingResponse = \false;
981 $easy->headers = [$value];
982 } else {
983 $easy->headers[] = $value;
984 }
985 return \strlen($h);
986 };
987 }
988 public function __destruct()
989 {
990 foreach ($this->handles as $id => $handle) {
991 if (\PHP_VERSION_ID < 80000) {
992 \curl_close($handle);
993 }
994 unset($this->handles[$id]);
995 }
996 }
997 }
998