Debian Codegraph @

lib/3rdParty/composer/guzzlehttp/guzzle/src/Handler/StreamHandler.php

raw symbols SCIP
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\TransferStats;
12 use GuzzleHttp\TransportSharing;
13 use GuzzleHttp\Utils;
14 use Psr\Http\Message\RequestInterface;
15 use Psr\Http\Message\ResponseInterface;
16 use Psr\Http\Message\StreamInterface;
17 use Psr\Http\Message\UriInterface;
18
19 /**
20 * HTTP handler that uses PHP's HTTP stream wrapper.
21 *
22 * @final
23 */
24 class StreamHandler
25 {
26 private const CONNECTION_ERRORS = [
27 'php_network_getaddresses:',
28 'getaddrinfo',
29 'gethostbyname failed',
30 'Connection refused',
31 'No connection could be made because the target machine actively refused it',
32 "couldn't connect to host", // error on HHVM
33 'connection attempt failed',
34 'connect() failed',
35 'Connection timed out',
36 'Operation timed out',
37 'Network is unreachable',
38 'No route to host',
39 'Host is unreachable',
40 'Host is down',
41 'Cannot connect to HTTPS server through proxy',
42 ];
43
44 /**
45 * @var array
46 */
47 private $lastHeaders = [];
48
49 /**
50 * @var string
51 */
52 private $transportSharingMode;
53
54 /**
55 * Accepts an associative array of options:
56 *
57 * - transport_sharing: Optional transport sharing mode.
58 *
59 * @param array{transport_sharing?: mixed} $options Array of options to use with the handler
60 */
61 public function __construct(array $options = [])
62 {
63 $this->transportSharingMode = CurlShareHandleState::normalizeMode(
64 $options['transport_sharing'] ?? null,
65 'transport_sharing'
66 );
67 }
68
69 /**
70 * Sends an HTTP request.
71 *
72 * @param RequestInterface $request Request to send.
73 * @param array $options Request transfer options.
74 */
75 public function __invoke(RequestInterface $request, array $options): PromiseInterface
76 {
77 // Sleep if there is a delay specified.
78 if (isset($options['delay'])) {
79 \usleep($options['delay'] * 1000);
80 }
81
82 $protocolVersion = $request->getProtocolVersion();
83
84 if ('' === $protocolVersion) {
85 \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.');
86
87 $protocolVersion = '1.1';
88 $request = Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
89 }
90
91 if ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
92 throw new ConnectException(sprintf('HTTP/%s is not supported by the stream handler.', $protocolVersion), $request);
93 }
94
95 $startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
96
97 self::triggerUnsupportedRequestOptionDeprecations($request, $options);
98 $this->assertTransportSharingSupported();
99
100 try {
101 // Does not support the expect header.
102 $request = $request->withoutHeader('Expect');
103
104 // Append a content-length header if body size is zero to match
105 // the behavior of `CurlHandler`
106 if (
107 (
108 0 === \strcasecmp('PUT', $request->getMethod())
109 || 0 === \strcasecmp('POST', $request->getMethod())
110 )
111 && 0 === $request->getBody()->getSize()
112 ) {
113 $request = $request->withHeader('Content-Length', '0');
114 }
115
116 return $this->createResponse(
117 $request,
118 $options,
119 $this->createStream($request, $options),
120 $startTime
121 );
122 } catch (\InvalidArgumentException $e) {
123 throw $e;
124 } catch (\Exception $e) {
125 // Determine if the error was a networking error.
126 if (self::isConnectionError($e->getMessage())) {
127 $e = new ConnectException($e->getMessage(), $request, $e);
128 } else {
129 $e = $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e);
130 }
131 $this->invokeStats($options, $request, $startTime, null, $e);
132
133 return P\Create::rejectionFor($e);
134 }
135 }
136
137 private static function isConnectionError(string $message): bool
138 {
139 foreach (self::CONNECTION_ERRORS as $connectionError) {
140 if (false !== \strpos($message, $connectionError)) {
141 return true;
142 }
143 }
144
145 return false;
146 }
147
148 private function invokeStats(
149 array $options,
150 RequestInterface $request,
151 ?float $startTime,
152 ?ResponseInterface $response = null,
153 ?\Throwable $error = null
154 ): void {
155 if (isset($options['on_stats'])) {
156 $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []);
157 ($options['on_stats'])($stats);
158 }
159 }
160
161 /**
162 * @param resource $stream
163 */
164 private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface
165 {
166 $hdrs = $this->lastHeaders;
167 $this->lastHeaders = [];
168
169 try {
170 [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs);
171 } catch (\Throwable $e) {
172 return $this->rejectResponseCreation($options, $request, $startTime, $e);
173 }
174
175 [$stream, $headers] = $this->checkDecode($options, $headers, $stream);
176 $stream = Psr7\Utils::streamFor($stream);
177 $sink = $stream;
178
179 if (\strcasecmp('HEAD', $request->getMethod())) {
180 $sink = $this->createSink($stream, $options);
181 }
182
183 try {
184 $response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
185 } catch (\Throwable $e) {
186 return $this->rejectResponseCreation($options, $request, $startTime, $e);
187 }
188
189 if (isset($options['on_headers'])) {
190 try {
191 $options['on_headers']($response);
192 } catch (\Throwable $e) {
193 return P\Create::rejectionFor(
194 new RequestException('An error was encountered during the on_headers event', $request, $response, $e)
195 );
196 }
197 }
198
199 // Do not drain when the request is a HEAD request because they have
200 // no body.
201 if ($sink !== $stream) {
202 $this->drain($stream, $sink, $response->getHeaderLine('Content-Length'));
203 }
204
205 $this->invokeStats($options, $request, $startTime, $response, null);
206
207 return new FulfilledPromise($response);
208 }
209
210 private function rejectResponseCreation(
211 array $options,
212 RequestInterface $request,
213 ?float $startTime,
214 \Throwable $previous
215 ): PromiseInterface {
216 $reason = new RequestException(
217 'An error was encountered while creating the response',
218 $request,
219 null,
220 $previous
221 );
222
223 $this->invokeStats($options, $request, $startTime, null, $reason);
224
225 return P\Create::rejectionFor($reason);
226 }
227
228 private function createSink(StreamInterface $stream, array $options): StreamInterface
229 {
230 if (!empty($options['stream'])) {
231 return $stream;
232 }
233
234 $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+');
235
236 return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink);
237 }
238
239 /**
240 * @param resource $stream
241 */
242 private function checkDecode(array $options, array $headers, $stream): array
243 {
244 // Automatically decode responses when instructed.
245 if (!empty($options['decode_content'])) {
246 $normalizedKeys = Utils::normalizeHeaderKeys($headers);
247 if (isset($normalizedKeys['content-encoding'])) {
248 $encoding = $headers[$normalizedKeys['content-encoding']];
249 if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') {
250 $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream));
251 $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
252
253 // Remove content-encoding header
254 unset($headers[$normalizedKeys['content-encoding']]);
255
256 // The decoded length cannot be known without inflating the
257 // stream, so keep the original length for inspection and
258 // drop the now-unknown Content-Length header.
259 if (isset($normalizedKeys['content-length'])) {
260 $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
261 unset($headers[$normalizedKeys['content-length']]);
262 }
263 }
264 }
265 }
266
267 return [$stream, $headers];
268 }
269
270 /**
271 * Drains the source stream into the "sink" client option.
272 *
273 * @param string $contentLength Header specifying the amount of
274 * data to read.
275 *
276 * @throws \RuntimeException when the sink option is invalid.
277 */
278 private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface
279 {
280 // If a content-length header is provided, then stop reading once
281 // that number of bytes has been read. This can prevent infinitely
282 // reading from a stream when dealing with servers that do not honor
283 // Connection: Close headers.
284 Psr7\Utils::copyToStream(
285 $source,
286 $sink,
287 (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1
288 );
289
290 $sink->seek(0);
291 $source->close();
292
293 return $sink;
294 }
295
296 /**
297 * Create a resource and check to ensure it was created successfully
298 *
299 * @param callable $callback Callable that returns stream resource
300 *
301 * @return resource
302 *
303 * @throws \RuntimeException on error
304 */
305 private function createResource(callable $callback)
306 {
307 $errors = [];
308 \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool {
309 $errors[] = [
310 'message' => $msg,
311 'file' => $file,
312 'line' => $line,
313 ];
314
315 return true;
316 });
317
318 try {
319 $resource = $callback();
320 } finally {
321 \restore_error_handler();
322 }
323
324 if (!$resource) {
325 $message = 'Error creating resource: ';
326 foreach ($errors as $err) {
327 foreach ($err as $key => $value) {
328 $message .= "[$key] $value".\PHP_EOL;
329 }
330 }
331 throw new \RuntimeException(\trim($message));
332 }
333
334 return $resource;
335 }
336
337 /**
338 * @return resource
339 */
340 private function createStream(RequestInterface $request, array $options)
341 {
342 static $methods;
343 if (!$methods) {
344 $methods = \array_flip(\get_class_methods(__CLASS__));
345 }
346
347 $scheme = $request->getUri()->getScheme();
348 if (!\in_array($scheme, ['http', 'https'], true)) {
349 throw new RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
350 }
351
352 $protocols = Utils::normalizeProtocols($options['protocols'] ?? ['http', 'https']);
353 if (!\in_array($scheme, $protocols, true)) {
354 throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $request);
355 }
356
357 // HTTP/1.1 streams using the PHP stream wrapper require a
358 // Connection: close header
359 if ($request->getProtocolVersion() === '1.1'
360 && !$request->hasHeader('Connection')
361 ) {
362 $request = $request->withHeader('Connection', 'close');
363 }
364
365 // Ensure SSL is verified by default
366 if (!isset($options['verify'])) {
367 $options['verify'] = true;
368 }
369
370 $params = [];
371 $context = $this->getDefaultContext($request);
372
373 if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) {
374 throw new \InvalidArgumentException('on_headers must be callable');
375 }
376
377 if (!empty($options)) {
378 foreach ($options as $key => $value) {
379 $method = "add_{$key}";
380 if (isset($methods[$method])) {
381 $this->{$method}($request, $context, $value, $params);
382 }
383 }
384 }
385
386 if (isset($options['stream_context'])) {
387 if (!\is_array($options['stream_context'])) {
388 throw new \InvalidArgumentException('stream_context must be an array');
389 }
390 $context = \array_replace_recursive($context, $options['stream_context']);
391 }
392
393 // Microsoft NTLM authentication only supported with curl handler
394 if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) {
395 throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler');
396 }
397
398 $uri = $this->resolveHost($request, $options);
399
400 $contextResource = $this->createResource(
401 static function () use ($context, $params) {
402 return \stream_context_create($context, $params);
403 }
404 );
405
406 return $this->createResource(
407 function () use ($uri, $contextResource, $context, $options, $request) {
408 $resource = @\fopen((string) $uri, 'r', false, $contextResource);
409
410 // See https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_the_http_response_header_predefined_variable
411 if (function_exists('http_get_last_response_headers')) {
412 $http_response_header = \http_get_last_response_headers();
413 }
414
415 $this->lastHeaders = $http_response_header ?? [];
416
417 if (false === $resource) {
418 throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context);
419 }
420
421 if (isset($options['read_timeout'])) {
422 $readTimeout = $options['read_timeout'];
423 $sec = (int) $readTimeout;
424 $usec = ($readTimeout - $sec) * 100000;
425 \stream_set_timeout($resource, $sec, $usec);
426 }
427
428 return $resource;
429 }
430 );
431 }
432
433 private function resolveHost(RequestInterface $request, array $options): UriInterface
434 {
435 $uri = $request->getUri();
436
437 if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) {
438 if ('v4' === $options['force_ip_resolve']) {
439 $records = \dns_get_record($uri->getHost(), \DNS_A);
440 if (false === $records || !isset($records[0]['ip'])) {
441 throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
442 }
443
444 return $uri->withHost($records[0]['ip']);
445 }
446 if ('v6' === $options['force_ip_resolve']) {
447 $records = \dns_get_record($uri->getHost(), \DNS_AAAA);
448 if (false === $records || !isset($records[0]['ipv6'])) {
449 throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
450 }
451
452 return $uri->withHost('['.$records[0]['ipv6'].']');
453 }
454 }
455
456 return $uri;
457 }
458
459 private function getDefaultContext(RequestInterface $request): array
460 {
461 $headers = '';
462 foreach ($request->getHeaders() as $name => $value) {
463 foreach ($value as $val) {
464 $headers .= "$name: $val\r\n";
465 }
466 }
467
468 $context = [
469 'http' => [
470 'method' => $request->getMethod(),
471 'header' => $headers,
472 'protocol_version' => $request->getProtocolVersion(),
473 'ignore_errors' => true,
474 'follow_location' => 0,
475 ],
476 'ssl' => [
477 'peer_name' => $request->getUri()->getHost(),
478 ],
479 ];
480
481 $body = (string) $request->getBody();
482
483 if ('' !== $body) {
484 $context['http']['content'] = $body;
485 // Prevent the HTTP handler from adding a Content-Type header.
486 if (!$request->hasHeader('Content-Type')) {
487 $context['http']['header'] .= "Content-Type:\r\n";
488 }
489 }
490
491 $context['http']['header'] = \rtrim($context['http']['header']);
492
493 return $context;
494 }
495
496 private static function triggerUnsupportedRequestOptionDeprecations(RequestInterface $request, array $options): void
497 {
498 if (
499 \array_key_exists('curl', $options)
500 && $options['curl'] !== null
501 && $options['curl'] !== []
502 && !self::isCurlOptionGeneratedByAuth($options)
503 ) {
504 \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "curl" request option to the stream handler is deprecated; guzzlehttp/guzzle 8.0 will reject this option because the stream handler ignores cURL options.');
505 }
506
507 if (self::usesDigestAuth($options)) {
508 \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing digest authentication to the stream handler is deprecated; guzzlehttp/guzzle 8.0 will reject digest authentication with the stream handler because it is only supported by cURL handlers.');
509 }
510
511 if (\array_key_exists('expect', $options) && $options['expect'] !== false && $request->hasHeader('Expect')) {
512 \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "expect" request option to the stream handler is deprecated when it adds an Expect header; guzzlehttp/guzzle 8.0 will reject this option because the stream handler does not support Expect: 100-Continue.');
513 }
514 }
515
516 private function assertTransportSharingSupported(): void
517 {
518 if ($this->transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
519 throw new \InvalidArgumentException('The "transport_sharing" option requires transport sharing, but the stream handler does not support it.');
520 }
521 }
522
523 private static function isCurlOptionGeneratedByAuth(array $options): bool
524 {
525 if (!isset($options['curl']) || !\is_array($options['curl']) || !isset($options['auth'][2]) || !\is_string($options['auth'][2])) {
526 return false;
527 }
528
529 if (!\defined('CURLOPT_HTTPAUTH') || !\defined('CURLOPT_USERPWD')) {
530 return false;
531 }
532
533 $type = \strtolower($options['auth'][2]);
534 if ($type === 'digest') {
535 $httpAuth = \defined('CURLAUTH_DIGEST') ? \constant('CURLAUTH_DIGEST') : null;
536 } elseif ($type === 'ntlm') {
537 $httpAuth = \defined('CURLAUTH_NTLM') ? \constant('CURLAUTH_NTLM') : null;
538 } else {
539 return false;
540 }
541
542 return $httpAuth !== null
543 && \count($options['curl']) === 2
544 && isset($options['curl'][\CURLOPT_HTTPAUTH], $options['curl'][\CURLOPT_USERPWD])
545 && $options['curl'][\CURLOPT_HTTPAUTH] === $httpAuth;
546 }
547
548 private static function usesDigestAuth(array $options): bool
549 {
550 return isset($options['auth'][2])
551 && \is_string($options['auth'][2])
552 && \strtolower($options['auth'][2]) === 'digest';
553 }
554
555 /**
556 * @param mixed $value as passed via Request transfer options.
557 *
558 * @return array{0: string, 1: string|null}
559 */
560 private static function normalizeTlsFileOption(string $option, $value): array
561 {
562 $passphrase = null;
563
564 if (\is_array($value)) {
565 if (!isset($value[0]) || !\is_string($value[0])) {
566 throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
567 }
568 if (isset($value[1])) {
569 if (!\is_string($value[1])) {
570 throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
571 }
572 $passphrase = $value[1];
573 }
574 $value = $value[0];
575 }
576
577 if (!\is_string($value)) {
578 throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
579 }
580
581 return [$value, $passphrase];
582 }
583
584 private static function setTlsPassphrase(array &$options, ?string $passphrase, string $option): void
585 {
586 if ($passphrase === null) {
587 return;
588 }
589
590 if (isset($options['ssl']['passphrase']) && $options['ssl']['passphrase'] !== $passphrase) {
591 throw new \InvalidArgumentException(\sprintf('Cannot use different passphrases for cert and ssl_key with the stream handler; %s conflicts with an existing TLS passphrase.', $option));
592 }
593
594 $options['ssl']['passphrase'] = $passphrase;
595 }
596
597 /**
598 * @param mixed $value as passed via Request transfer options.
599 */
600 private static function assertStreamTlsType(string $option, $value): void
601 {
602 if (!\is_string($value) || $value === '') {
603 throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
604 }
605
606 if (\strtoupper($value) !== 'PEM') {
607 throw new \InvalidArgumentException(\sprintf('The stream handler only supports "PEM" for the %s request option.', $option));
608 }
609 }
610
611 /**
612 * @param mixed $value as passed via Request transfer options.
613 */
614 private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void
615 {
616 $uri = null;
617
618 if (!\is_array($value)) {
619 $uri = $value;
620 } else {
621 $scheme = $request->getUri()->getScheme();
622 if (isset($value[$scheme])) {
623 if (
624 !isset($value['no'])
625 || !Utils::isUriInNoProxy($request->getUri(), $value['no'])
626 ) {
627 $uri = $value[$scheme];
628 }
629 }
630 }
631
632 if (!$uri) {
633 return;
634 }
635
636 $parsed = $this->parse_proxy($uri);
637 $options['http']['proxy'] = $parsed['proxy'];
638
639 if ($parsed['auth']) {
640 if (!isset($options['http']['header'])) {
641 $options['http']['header'] = [];
642 }
643 $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}";
644 }
645 }
646
647 /**
648 * Parses the given proxy URL to make it compatible with the format PHP's stream context expects.
649 */
650 private function parse_proxy(string $url): array
651 {
652 $parsed = \parse_url($url);
653
654 if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
655 if (isset($parsed['host']) && isset($parsed['port'])) {
656 $auth = null;
657 if (isset($parsed['user']) && isset($parsed['pass'])) {
658 $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}");
659 }
660
661 return [
662 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}",
663 'auth' => $auth ? "Basic {$auth}" : null,
664 ];
665 }
666 }
667
668 // Return proxy as-is.
669 return [
670 'proxy' => $url,
671 'auth' => null,
672 ];
673 }
674
675 /**
676 * @param mixed $value as passed via Request transfer options.
677 */
678 private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void
679 {
680 if ($value > 0) {
681 $options['http']['timeout'] = $value;
682 }
683 }
684
685 /**
686 * @param mixed $value as passed via Request transfer options.
687 */
688 private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void
689 {
690 if (
691 $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
692 || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
693 || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
694 || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT)
695 ) {
696 $options['http']['crypto_method'] = $value;
697
698 return;
699 }
700
701 throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
702 }
703
704 /**
705 * @param mixed $value as passed via Request transfer options.
706 */
707 private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void
708 {
709 if ($value === false) {
710 $options['ssl']['verify_peer'] = false;
711 $options['ssl']['verify_peer_name'] = false;
712
713 return;
714 }
715
716 if (\is_string($value)) {
717 $options['ssl']['cafile'] = $value;
718 if (!\file_exists($value)) {
719 throw new \RuntimeException("SSL CA bundle not found: $value");
720 }
721 } elseif ($value !== true) {
722 throw new \InvalidArgumentException('Invalid verify request option');
723 }
724
725 $options['ssl']['verify_peer'] = true;
726 $options['ssl']['verify_peer_name'] = true;
727 $options['ssl']['allow_self_signed'] = false;
728 }
729
730 /**
731 * @param mixed $value as passed via Request transfer options.
732 */
733 private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void
734 {
735 [$value, $passphrase] = self::normalizeTlsFileOption('cert', $value);
736
737 if (!\file_exists($value)) {
738 throw new \RuntimeException("SSL certificate not found: {$value}");
739 }
740
741 self::setTlsPassphrase($options, $passphrase, 'cert');
742 $options['ssl']['local_cert'] = $value;
743 }
744
745 /**
746 * @param mixed $value as passed via Request transfer options.
747 */
748 private function add_cert_type(RequestInterface $request, array &$options, $value, array &$params): void
749 {
750 self::assertStreamTlsType('cert_type', $value);
751 }
752
753 /**
754 * @param mixed $value as passed via Request transfer options.
755 */
756 private function add_ssl_key(RequestInterface $request, array &$options, $value, array &$params): void
757 {
758 [$value, $passphrase] = self::normalizeTlsFileOption('ssl_key', $value);
759
760 if (!\file_exists($value)) {
761 throw new \RuntimeException("SSL private key not found: {$value}");
762 }
763
764 self::setTlsPassphrase($options, $passphrase, 'ssl_key');
765 $options['ssl']['local_pk'] = $value;
766 }
767
768 /**
769 * @param mixed $value as passed via Request transfer options.
770 */
771 private function add_ssl_key_type(RequestInterface $request, array &$options, $value, array &$params): void
772 {
773 self::assertStreamTlsType('ssl_key_type', $value);
774 }
775
776 /**
777 * @param mixed $value as passed via Request transfer options.
778 */
779 private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void
780 {
781 if (!\is_callable($value)) {
782 throw new \InvalidArgumentException('progress client option must be callable');
783 }
784
785 self::addNotification(
786 $params,
787 static function ($code, $a, $b, $c, $transferred, $total) use ($value) {
788 if ($code == \STREAM_NOTIFY_PROGRESS) {
789 // The upload progress cannot be determined. Use 0 for cURL compatibility:
790 // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html
791 $value($total, $transferred, 0, 0);
792 }
793 }
794 );
795 }
796
797 /**
798 * @param mixed $value as passed via Request transfer options.
799 */
800 private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void
801 {
802 if ($value === false) {
803 return;
804 }
805
806 static $map = [
807 \STREAM_NOTIFY_CONNECT => 'CONNECT',
808 \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
809 \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
810 \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
811 \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
812 \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
813 \STREAM_NOTIFY_PROGRESS => 'PROGRESS',
814 \STREAM_NOTIFY_FAILURE => 'FAILURE',
815 \STREAM_NOTIFY_COMPLETED => 'COMPLETED',
816 \STREAM_NOTIFY_RESOLVE => 'RESOLVE',
817 ];
818 static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max'];
819
820 $value = Utils::debugResource($value);
821 $ident = $request->getMethod().' '.$request->getUri()->withFragment('');
822 self::addNotification(
823 $params,
824 static function (int $code, ...$passed) use ($ident, $value, $map, $args): void {
825 \fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
826 foreach (\array_filter($passed) as $i => $v) {
827 \fwrite($value, $args[$i].': "'.$v.'" ');
828 }
829 \fwrite($value, "\n");
830 }
831 );
832 }
833
834 private static function addNotification(array &$params, callable $notify): void
835 {
836 // Wrap the existing function if needed.
837 if (!isset($params['notification'])) {
838 $params['notification'] = $notify;
839 } else {
840 $params['notification'] = self::callArray([
841 $params['notification'],
842 $notify,
843 ]);
844 }
845 }
846
847 private static function callArray(array $functions): callable
848 {
849 return static function (...$args) use ($functions) {
850 foreach ($functions as $fn) {
851 $fn(...$args);
852 }
853 };
854 }
855 }