PluginProbe
Gmail SMTP / trunk
Gmail SMTP vtrunk
1.2.3.21 1.2.3.20 trunk 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.9 1.2.0 1.2.3.14 1.2.3.15 1.2.3.16 1.2.3.18 1.2.3.5
gmail-smtp / google-api-php-client / vendor / guzzlehttp / guzzle / src / Handler / CurlFactory.php

CurlFactory.php in Gmail SMTP trunk, at google-api-php-client/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php

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