Debian Codegraph @

vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php

raw
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 (isset($options['decode_content']) && $options['decode_content'] !== false) {
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 $uri = $request->getUri();
348 $scheme = $uri->getScheme();
349 if ($scheme === '') {
350 throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request);
351 }
352
353 if (!\in_array($scheme, ['http', 'https'], true)) {
354 throw new RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
355 }
356
357 $protocols = Utils::normalizeProtocols($options['protocols'] ?? ['http', 'https']);
358 if (!\in_array($scheme, $protocols, true)) {
359 throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $request);
360 }
361
362 if ($uri->getHost() === '') {
363 throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request);
364 }
365
366 // HTTP/1.1 streams using the PHP stream wrapper require a
367 // Connection: close header
368 if ($request->getProtocolVersion() === '1.1'
369 && !$request->hasHeader('Connection')
370 ) {
371 $request = $request->withHeader('Connection', 'close');
372 }
373
374 // Ensure SSL is verified by default
375 if (!isset($options['verify'])) {
376 $options['verify'] = true;
377 }
378
379 $params = [];
380 $context = $this->getDefaultContext($request);
381
382 if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) {
383 throw new \InvalidArgumentException('on_headers must be callable');
384 }
385
386 self::assertTlsVersionRangeForOptions($options);
387
388 if (!empty($options)) {
389 foreach ($options as $key => $value) {
390 $method = "add_{$key}";
391 if (isset($methods[$method])) {
392 $this->{$method}($request, $context, $value, $params);
393 }
394 }
395 }
396
397 if (isset($options['stream_context'])) {
398 if (!\is_array($options['stream_context'])) {
399 throw new \InvalidArgumentException('stream_context must be an array');
400 }
401 self::triggerConflictingStreamContextOptionDeprecations($options['stream_context']);
402 self::triggerUnsupportedStreamContextOptionDeprecations($options['stream_context']);
403 $context = \array_replace_recursive($context, $options['stream_context']);
404 }
405
406 // Microsoft NTLM authentication only supported with curl handler
407 if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) {
408 throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler');
409 }
410
411 $uri = $this->resolveHost($request, $options);
412
413 $contextResource = $this->createResource(
414 static function () use ($context, $params) {
415 return \stream_context_create($context, $params);
416 }
417 );
418
419 return $this->createResource(
420 function () use ($uri, $contextResource, $context, $options, $request) {
421 $resource = @\fopen((string) $uri, 'r', false, $contextResource);
422
423 // See https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_the_http_response_header_predefined_variable
424 if (function_exists('http_get_last_response_headers')) {
425 $http_response_header = \http_get_last_response_headers();
426 }
427
428 $this->lastHeaders = $http_response_header ?? [];
429
430 if (false === $resource) {
431 throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context);
432 }
433
434 if (isset($options['read_timeout'])) {
435 $readTimeout = $options['read_timeout'];
436 $sec = (int) $readTimeout;
437 $usec = ($readTimeout - $sec) * 100000;
438 \stream_set_timeout($resource, $sec, $usec);
439 }
440
441 return $resource;
442 }
443 );
444 }
445
446 private function resolveHost(RequestInterface $request, array $options): UriInterface
447 {
448 $uri = $request->getUri();
449
450 $host = $uri->getHost();
451 $hostForIpCheck = $host !== '' && $host[0] === '[' && \substr($host, -1) === ']'
452 ? \substr($host, 1, -1)
453 : $host;
454 if (isset($options['force_ip_resolve']) && !\filter_var($hostForIpCheck, \FILTER_VALIDATE_IP)) {
455 if ('v4' === $options['force_ip_resolve']) {
456 $records = \dns_get_record($uri->getHost(), \DNS_A);
457 if (false === $records || !isset($records[0]['ip'])) {
458 throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
459 }
460
461 return $uri->withHost($records[0]['ip']);
462 }
463 if ('v6' === $options['force_ip_resolve']) {
464 $records = \dns_get_record($uri->getHost(), \DNS_AAAA);
465 if (false === $records || !isset($records[0]['ipv6'])) {
466 throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
467 }
468
469 return $uri->withHost('['.$records[0]['ipv6'].']');
470 }
471 }
472
473 return $uri;
474 }
475
476 private function getDefaultContext(RequestInterface $request): array
477 {
478 $headers = '';
479 foreach ($request->getHeaders() as $name => $value) {
480 foreach ($value as $val) {
481 $headers .= "$name: $val\r\n";
482 }
483 }
484
485 $context = [
486 'http' => [
487 'method' => $request->getMethod(),
488 'header' => $headers,
489 'protocol_version' => $request->getProtocolVersion(),
490 'ignore_errors' => true,
491 'follow_location' => 0,
492 ],
493 'ssl' => [
494 'peer_name' => $request->getUri()->getHost(),
495 ],
496 ];
497
498 $body = (string) $request->getBody();
499
500 if ('' !== $body) {
501 $context['http']['content'] = $body;
502 // Prevent the HTTP handler from adding a Content-Type header.
503 if (!$request->hasHeader('Content-Type')) {
504 $context['http']['header'] .= "Content-Type:\r\n";
505 }
506 }
507
508 $context['http']['header'] = \rtrim($context['http']['header']);
509
510 return $context;
511 }
512
513 private static function triggerUnsupportedRequestOptionDeprecations(RequestInterface $request, array $options): void
514 {
515 if (
516 \array_key_exists('curl', $options)
517 && $options['curl'] !== null
518 && $options['curl'] !== []
519 && !self::isCurlOptionGeneratedByAuth($options)
520 ) {
521 \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.');
522 }
523
524 if (\array_key_exists('expect', $options) && $options['expect'] !== false && $request->hasHeader('Expect')) {
525 \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.');
526 }
527 }
528
529 private static function triggerConflictingStreamContextOptionDeprecations(array $streamContext): void
530 {
531 $conflictingOptions = self::conflictingStreamContextOptions();
532
533 foreach ($streamContext as $wrapper => $contextOptions) {
534 if (!\is_string($wrapper) || !isset($conflictingOptions[$wrapper]) || !\is_array($contextOptions)) {
535 continue;
536 }
537
538 foreach ($contextOptions as $option => $_) {
539 if (!\is_string($option) || !\array_key_exists($option, $conflictingOptions[$wrapper])) {
540 continue;
541 }
542
543 \trigger_deprecation(
544 'guzzlehttp/guzzle',
545 '7.12',
546 \sprintf(
547 'Passing stream_context.%s.%s in the "stream_context" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed request handling. Use %s instead.',
548 $wrapper,
549 $option,
550 $conflictingOptions[$wrapper][$option]
551 )
552 );
553 }
554 }
555 }
556
557 private static function triggerUnsupportedStreamContextOptionDeprecations(array $streamContext): void
558 {
559 $unsupportedOptions = self::unsupportedStreamContextOptions($streamContext);
560 if ($unsupportedOptions === []) {
561 return;
562 }
563
564 \trigger_deprecation(
565 'guzzlehttp/guzzle',
566 '7.12',
567 \sprintf(
568 'Passing PHP stream context options outside the built-in stream handler allow-list to the "stream_context" request option is deprecated; guzzlehttp/guzzle 8.0 will reject stream context options outside the allow-list. Deprecated option%s: %s.',
569 \count($unsupportedOptions) === 1 ? '' : 's',
570 \implode(', ', $unsupportedOptions)
571 )
572 );
573 }
574
575 /**
576 * @return string[]
577 */
578 private static function unsupportedStreamContextOptions(array $streamContext): array
579 {
580 $supportedOptions = self::supportedStreamContextOptions();
581 $conflictingOptions = self::conflictingStreamContextOptions();
582 $unsupportedOptions = [];
583
584 foreach ($streamContext as $wrapper => $contextOptions) {
585 if (!\is_string($wrapper) || !isset($supportedOptions[$wrapper])) {
586 if (\is_array($contextOptions)) {
587 foreach ($contextOptions as $option => $_) {
588 if (\is_string($wrapper) && \is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) {
589 continue;
590 }
591
592 $unsupportedOptions[] = \sprintf('stream_context.%s.%s', (string) $wrapper, (string) $option);
593 }
594 } else {
595 $unsupportedOptions[] = \sprintf('stream_context.%s', (string) $wrapper);
596 }
597
598 continue;
599 }
600
601 if (!\is_array($contextOptions)) {
602 $unsupportedOptions[] = \sprintf('stream_context.%s', $wrapper);
603
604 continue;
605 }
606
607 foreach ($contextOptions as $option => $_) {
608 if (\is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) {
609 continue;
610 }
611
612 if (!\is_string($option) || !\array_key_exists($option, $supportedOptions[$wrapper])) {
613 $unsupportedOptions[] = \sprintf('stream_context.%s.%s', $wrapper, (string) $option);
614 }
615 }
616 }
617
618 return $unsupportedOptions;
619 }
620
621 /**
622 * @return array<string, array<string, true>>
623 */
624 private static function supportedStreamContextOptions(): array
625 {
626 return [
627 'http' => [
628 'request_fulluri' => true,
629 ],
630 'socket' => [
631 'bindto' => true,
632 'tcp_nodelay' => true,
633 ],
634 'ssl' => [
635 'SNI_enabled' => true,
636 'capture_peer_cert' => true,
637 'capture_peer_cert_chain' => true,
638 'ciphers' => true,
639 'disable_compression' => true,
640 'no_ticket' => true,
641 'peer_fingerprint' => true,
642 'security_level' => true,
643 'verify_depth' => true,
644 ],
645 ];
646 }
647
648 /**
649 * @return array<string, array<string, string>>
650 */
651 private static function conflictingStreamContextOptions(): array
652 {
653 return [
654 'http' => [
655 'content' => 'the request body',
656 'follow_location' => 'the "allow_redirects" request option',
657 'header' => 'the request headers',
658 'max_redirects' => 'the "allow_redirects" request option',
659 'method' => 'the request method',
660 'protocol_version' => 'the request protocol version',
661 'proxy' => 'the "proxy" request option',
662 'timeout' => 'the "timeout" request option',
663 ],
664 'ssl' => [
665 'allow_self_signed' => 'the "verify" request option',
666 'cafile' => 'the "verify" request option',
667 'capath' => 'the "verify" request option',
668 'crypto_method' => 'the "crypto_method" request option',
669 'local_cert' => 'the "cert" request option',
670 'local_pk' => 'the "ssl_key" request option',
671 'max_proto_version' => 'the "crypto_method_max" request option',
672 'min_proto_version' => 'the "crypto_method" request option',
673 'passphrase' => 'the "cert" or "ssl_key" request option',
674 'peer_name' => 'the request URI',
675 'verify_peer' => 'the "verify" request option',
676 'verify_peer_name' => 'the "verify" request option',
677 ],
678 ];
679 }
680
681 private function assertTransportSharingSupported(): void
682 {
683 if ($this->transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
684 throw new \InvalidArgumentException('The "transport_sharing" option requires transport sharing, but the stream handler does not support it.');
685 }
686 }
687
688 private static function isCurlOptionGeneratedByAuth(array $options): bool
689 {
690 if (!isset($options['curl']) || !\is_array($options['curl']) || !isset($options['auth'][2]) || !\is_string($options['auth'][2])) {
691 return false;
692 }
693
694 if (!\defined('CURLOPT_HTTPAUTH') || !\defined('CURLOPT_USERPWD')) {
695 return false;
696 }
697
698 $type = \strtolower($options['auth'][2]);
699 if ($type === 'digest') {
700 $httpAuth = \defined('CURLAUTH_DIGEST') ? \constant('CURLAUTH_DIGEST') : null;
701 } elseif ($type === 'ntlm') {
702 $httpAuth = \defined('CURLAUTH_NTLM') ? \constant('CURLAUTH_NTLM') : null;
703 } else {
704 return false;
705 }
706
707 return $httpAuth !== null
708 && \count($options['curl']) === 2
709 && isset($options['curl'][\CURLOPT_HTTPAUTH], $options['curl'][\CURLOPT_USERPWD])
710 && $options['curl'][\CURLOPT_HTTPAUTH] === $httpAuth;
711 }
712
713 /**
714 * @param mixed $value as passed via Request transfer options.
715 *
716 * @return array{0: string, 1: string|null}
717 */
718 private static function normalizeTlsFileOption(string $option, $value): array
719 {
720 $passphrase = null;
721
722 if (\is_array($value)) {
723 if (!isset($value[0]) || !\is_string($value[0])) {
724 throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
725 }
726 if (isset($value[1])) {
727 if (!\is_string($value[1])) {
728 throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
729 }
730 $passphrase = $value[1];
731 }
732 $value = $value[0];
733 }
734
735 if (!\is_string($value)) {
736 throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
737 }
738
739 return [$value, $passphrase];
740 }
741
742 private static function setTlsPassphrase(array &$options, ?string $passphrase, string $option): void
743 {
744 if ($passphrase === null) {
745 return;
746 }
747
748 if (isset($options['ssl']['passphrase']) && $options['ssl']['passphrase'] !== $passphrase) {
749 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));
750 }
751
752 $options['ssl']['passphrase'] = $passphrase;
753 }
754
755 /**
756 * @param mixed $value as passed via Request transfer options.
757 */
758 private static function assertStreamTlsType(string $option, $value): void
759 {
760 if (!\is_string($value) || $value === '') {
761 throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
762 }
763
764 if (\strtoupper($value) !== 'PEM') {
765 throw new \InvalidArgumentException(\sprintf('The stream handler only supports "PEM" for the %s request option.', $option));
766 }
767 }
768
769 /**
770 * @param mixed $value as passed via Request transfer options.
771 */
772 private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void
773 {
774 $uri = null;
775
776 if (!\is_array($value)) {
777 $uri = $value;
778 } else {
779 $scheme = $request->getUri()->getScheme();
780 if (isset($value[$scheme])) {
781 if (
782 !isset($value['no'])
783 || !Utils::isUriInNoProxy($request->getUri(), $value['no'])
784 ) {
785 $uri = $value[$scheme];
786 }
787 }
788 }
789
790 if (!$uri) {
791 return;
792 }
793
794 $parsed = $this->parse_proxy($uri);
795 $options['http']['proxy'] = $parsed['proxy'];
796
797 if ($parsed['auth']) {
798 if (!isset($options['http']['header'])) {
799 $options['http']['header'] = '';
800 }
801 $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}";
802 }
803 }
804
805 /**
806 * Parses the given proxy URL to make it compatible with the format PHP's stream context expects.
807 */
808 private function parse_proxy(string $url): array
809 {
810 $parsed = \parse_url($url);
811
812 // parse_url() misreads scheme-less proxy authorities like
813 // "user:pass@host"; re-parse only those forms as HTTP.
814 $schemeLessAuthority = \strpos($url, '://') === false && \strncmp($url, '//', 2) !== 0;
815 if ($schemeLessAuthority) {
816 if (\is_array($parsed) && !isset($parsed['scheme']) && isset($parsed['host'], $parsed['port'])) {
817 $parsed['scheme'] = 'http';
818 } elseif (
819 (!\is_array($parsed) || !isset($parsed['host']))
820 && (\strpos($url, '@') !== false || \strncmp($url, '[', 1) === 0)
821 ) {
822 $parsed = \parse_url('http://'.$url);
823 }
824 }
825
826 if (\is_array($parsed) && isset($parsed['scheme']) && \strcasecmp($parsed['scheme'], 'http') === 0) {
827 if (isset($parsed['host'], $parsed['port'])) {
828 $user = $parsed['user'] ?? '';
829 $pass = $parsed['pass'] ?? '';
830 $auth = ($user !== '' || $pass !== '') ? 'Basic '.\base64_encode("{$user}:{$pass}") : null;
831
832 return [
833 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}",
834 'auth' => $auth,
835 ];
836 }
837 }
838
839 // Return proxy as-is.
840 return [
841 'proxy' => $url,
842 'auth' => null,
843 ];
844 }
845
846 /**
847 * @param mixed $value as passed via Request transfer options.
848 */
849 private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void
850 {
851 if ($value > 0) {
852 $options['http']['timeout'] = $value;
853 }
854 }
855
856 /**
857 * @param mixed $value as passed via Request transfer options.
858 */
859 private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void
860 {
861 if (
862 $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
863 || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
864 || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
865 || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT)
866 ) {
867 $options['http']['crypto_method'] = $value;
868
869 return;
870 }
871
872 throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
873 }
874
875 /**
876 * @param mixed $value as passed via Request transfer options.
877 */
878 private function add_crypto_method_max(RequestInterface $request, array &$options, $value, array &$params): void
879 {
880 $options['ssl']['max_proto_version'] = TlsVersion::streamProtocolVersion('crypto_method_max', $value);
881 }
882
883 private static function assertTlsVersionRangeForOptions(array $options): void
884 {
885 if (!isset($options['crypto_method_max'])) {
886 return;
887 }
888
889 TlsVersion::assertRange(
890 $options['crypto_method'] ?? null,
891 $options['crypto_method_max']
892 );
893 }
894
895 /**
896 * @param mixed $value as passed via Request transfer options.
897 */
898 private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void
899 {
900 if ($value === false) {
901 $options['ssl']['verify_peer'] = false;
902 $options['ssl']['verify_peer_name'] = false;
903
904 return;
905 }
906
907 if (\is_string($value)) {
908 $options['ssl']['cafile'] = $value;
909 if (!\file_exists($value)) {
910 throw new \RuntimeException("SSL CA bundle not found: $value");
911 }
912 } elseif ($value !== true) {
913 throw new \InvalidArgumentException('Invalid verify request option');
914 }
915
916 $options['ssl']['verify_peer'] = true;
917 $options['ssl']['verify_peer_name'] = true;
918 $options['ssl']['allow_self_signed'] = false;
919 }
920
921 /**
922 * @param mixed $value as passed via Request transfer options.
923 */
924 private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void
925 {
926 [$value, $passphrase] = self::normalizeTlsFileOption('cert', $value);
927
928 if (!\file_exists($value)) {
929 throw new \RuntimeException("SSL certificate not found: {$value}");
930 }
931
932 self::setTlsPassphrase($options, $passphrase, 'cert');
933 $options['ssl']['local_cert'] = $value;
934 }
935
936 /**
937 * @param mixed $value as passed via Request transfer options.
938 */
939 private function add_cert_type(RequestInterface $request, array &$options, $value, array &$params): void
940 {
941 self::assertStreamTlsType('cert_type', $value);
942 }
943
944 /**
945 * @param mixed $value as passed via Request transfer options.
946 */
947 private function add_ssl_key(RequestInterface $request, array &$options, $value, array &$params): void
948 {
949 [$value, $passphrase] = self::normalizeTlsFileOption('ssl_key', $value);
950
951 if (!\file_exists($value)) {
952 throw new \RuntimeException("SSL private key not found: {$value}");
953 }
954
955 self::setTlsPassphrase($options, $passphrase, 'ssl_key');
956 $options['ssl']['local_pk'] = $value;
957 }
958
959 /**
960 * @param mixed $value as passed via Request transfer options.
961 */
962 private function add_ssl_key_type(RequestInterface $request, array &$options, $value, array &$params): void
963 {
964 self::assertStreamTlsType('ssl_key_type', $value);
965 }
966
967 /**
968 * @param mixed $value as passed via Request transfer options.
969 */
970 private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void
971 {
972 if (!\is_callable($value)) {
973 throw new \InvalidArgumentException('progress client option must be callable');
974 }
975
976 self::addNotification(
977 $params,
978 static function ($code, $a, $b, $c, $transferred, $total) use ($value) {
979 if ($code == \STREAM_NOTIFY_PROGRESS) {
980 // The upload progress cannot be determined. Use 0 for cURL compatibility:
981 // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html
982 $value($total, $transferred, 0, 0);
983 }
984 }
985 );
986 }
987
988 /**
989 * @param mixed $value as passed via Request transfer options.
990 */
991 private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void
992 {
993 if ($value === false) {
994 return;
995 }
996
997 static $map = [
998 \STREAM_NOTIFY_CONNECT => 'CONNECT',
999 \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
1000 \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
1001 \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
1002 \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
1003 \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
1004 \STREAM_NOTIFY_PROGRESS => 'PROGRESS',
1005 \STREAM_NOTIFY_FAILURE => 'FAILURE',
1006 \STREAM_NOTIFY_COMPLETED => 'COMPLETED',
1007 \STREAM_NOTIFY_RESOLVE => 'RESOLVE',
1008 ];
1009 static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max'];
1010
1011 $value = Utils::debugResource($value);
1012 $ident = $request->getMethod().' '.$request->getUri()->withFragment('');
1013 self::addNotification(
1014 $params,
1015 static function (int $code, ...$passed) use ($ident, $value, $map, $args): void {
1016 \fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
1017 foreach (\array_filter($passed) as $i => $v) {
1018 \fwrite($value, $args[$i].': "'.$v.'" ');
1019 }
1020 \fwrite($value, "\n");
1021 }
1022 );
1023 }
1024
1025 private static function addNotification(array &$params, callable $notify): void
1026 {
1027 // Wrap the existing function if needed.
1028 if (!isset($params['notification'])) {
1029 $params['notification'] = $notify;
1030 } else {
1031 $params['notification'] = self::callArray([
1032 $params['notification'],
1033 $notify,
1034 ]);
1035 }
1036 }
1037
1038 private static function callArray(array $functions): callable
1039 {
1040 return static function (...$args) use ($functions) {
1041 foreach ($functions as $fn) {
1042 $fn(...$args);
1043 }
1044 };
1045 }
1046 }