Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/Response/CurlResponse.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpClient\Response;
13
14 use Psr\Log\LoggerInterface;
15 use Symfony\Component\HttpClient\Chunk\FirstChunk;
16 use Symfony\Component\HttpClient\Chunk\InformationalChunk;
17 use Symfony\Component\HttpClient\Exception\TransportException;
18 use Symfony\Component\HttpClient\Internal\Canary;
19 use Symfony\Component\HttpClient\Internal\ClientState;
20 use Symfony\Component\HttpClient\Internal\CurlClientState;
21 use Symfony\Contracts\HttpClient\ResponseInterface;
22
23 /**
24 * @author Nicolas Grekas <[email protected]>
25 *
26 * @internal
27 */
28 final class CurlResponse implements ResponseInterface, StreamableInterface
29 {
30 use CommonResponseTrait {
31 getContent as private doGetContent;
32 }
33 use TransportResponseTrait;
34
35 /**
36 * @var resource
37 */
38 private $debugBuffer;
39
40 /**
41 * @internal
42 */
43 public function __construct(
44 private CurlClientState $multi,
45 \CurlHandle|string $ch,
46 ?array $options = null,
47 ?LoggerInterface $logger = null,
48 string $method = 'GET',
49 ?callable $resolveRedirect = null,
50 ?int $curlVersion = null,
51 ?string $originalUrl = null,
52 private ?string $ntlmOriginKey = null,
53 ) {
54 if ($ch instanceof \CurlHandle) {
55 $this->handle = $ch;
56 $this->debugBuffer = fopen('php://temp', 'w+');
57 if (0x074000 === $curlVersion) {
58 fwrite($this->debugBuffer, 'Due to a bug in curl 7.64.0, the debug log is disabled; use another version to work around the issue.');
59 } else {
60 curl_setopt($ch, \CURLOPT_VERBOSE, true);
61 curl_setopt($ch, \CURLOPT_STDERR, $this->debugBuffer);
62 }
63 } else {
64 $this->info['url'] = $ch;
65 $ch = $this->handle;
66 }
67
68 $this->id = $id = (int) $ch;
69 $this->logger = $logger;
70 $this->shouldBuffer = $options['buffer'] ?? true;
71 $this->timeout = $options['timeout'] ?? null;
72 $this->info['http_method'] = $method;
73 $this->info['user_data'] = $options['user_data'] ?? null;
74 $this->info['max_duration'] = $options['max_duration'] ?? null;
75 $this->info['start_time'] ??= microtime(true);
76 $this->info['original_url'] = $originalUrl ?? $this->info['url'] ?? curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL);
77 $info = &$this->info;
78 $headers = &$this->headers;
79 $debugBuffer = $this->debugBuffer;
80
81 if (!$info['response_headers']) {
82 // Used to keep track of what we're waiting for
83 curl_setopt($ch, \CURLOPT_PRIVATE, \in_array($method, ['GET', 'HEAD', 'OPTIONS', 'TRACE', 'QUERY'], true) && 1.0 < (float) ($options['http_version'] ?? 1.1) ? 'H2' : 'H0'); // H = headers + retry counter
84 }
85
86 curl_setopt($ch, \CURLOPT_HEADERFUNCTION, static function ($ch, string $data) use (&$info, &$headers, $options, $multi, $id, &$location, $resolveRedirect, $logger): int {
87 return self::parseHeaderLine($ch, $data, $info, $headers, $options, $multi, $id, $location, $resolveRedirect, $logger);
88 });
89
90 if (null === $options) {
91 // Pushed response: buffer until requested
92 curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int {
93 $multi->handlesActivity[$id][] = $data;
94 curl_pause($ch, \CURLPAUSE_RECV);
95
96 return \strlen($data);
97 });
98
99 return;
100 }
101
102 $execCounter = $multi->execCounter;
103 $this->info['pause_handler'] = static function (float $duration) use ($ch, $multi, $execCounter) {
104 if (0 < $duration) {
105 if ($execCounter === $multi->execCounter) {
106 curl_multi_remove_handle($multi->handle, $ch);
107 }
108
109 $lastExpiry = end($multi->pauseExpiries);
110 $multi->pauseExpiries[(int) $ch] = $duration += hrtime(true) / 1E9;
111 if (false !== $lastExpiry && $lastExpiry > $duration) {
112 asort($multi->pauseExpiries);
113 }
114 curl_pause($ch, \CURLPAUSE_ALL);
115 } else {
116 unset($multi->pauseExpiries[(int) $ch]);
117 curl_pause($ch, \CURLPAUSE_CONT);
118 curl_multi_add_handle($multi->handle, $ch);
119 }
120 };
121
122 $this->inflate = !isset($options['normalized_headers']['accept-encoding']);
123 curl_pause($ch, \CURLPAUSE_CONT);
124
125 if ($onProgress = $options['on_progress']) {
126 $url = isset($info['url']) ? ['url' => $info['url']] : [];
127 curl_setopt($ch, \CURLOPT_NOPROGRESS, false);
128 curl_setopt($ch, \CURLOPT_PROGRESSFUNCTION, static function ($ch, $dlSize, $dlNow) use ($onProgress, &$info, $url, $multi, $debugBuffer) {
129 try {
130 $info['debug'] ??= '';
131 rewind($debugBuffer);
132 if (fstat($debugBuffer)['size']) {
133 $info['debug'] .= stream_get_contents($debugBuffer);
134 rewind($debugBuffer);
135 ftruncate($debugBuffer, 0);
136 }
137 $onProgress($dlNow, $dlSize, $url + curl_getinfo($ch) + $info);
138 } catch (\Throwable $e) {
139 $multi->handlesActivity[(int) $ch][] = null;
140 $multi->handlesActivity[(int) $ch][] = $e;
141
142 return 1; // Abort the request
143 }
144
145 return null;
146 });
147 }
148
149 curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int {
150 if ('H' === (curl_getinfo($ch, \CURLINFO_PRIVATE)[0] ?? null)) {
151 $multi->handlesActivity[$id][] = null;
152 $multi->handlesActivity[$id][] = new TransportException(\sprintf('Unsupported protocol for "%s"', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
153
154 return 0;
155 }
156
157 curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int {
158 $multi->handlesActivity[$id][] = $data;
159
160 return \strlen($data);
161 });
162
163 $multi->handlesActivity[$id][] = $data;
164
165 return \strlen($data);
166 });
167
168 $this->initializer = static function (self $response) {
169 $waitFor = curl_getinfo($response->handle, \CURLINFO_PRIVATE);
170
171 return 'H' === $waitFor[0];
172 };
173
174 // Schedule the request in a non-blocking way
175 $multi->lastTimeout = null;
176 $multi->openHandles[$id] = [$ch, $options];
177 curl_multi_add_handle($multi->handle, $ch);
178
179 $this->canary = new Canary(static function () use ($ch, $multi, $id) {
180 unset($multi->pauseExpiries[$id], $multi->openHandles[$id], $multi->handlesActivity[$id]);
181 curl_setopt($ch, \CURLOPT_PRIVATE, '_0');
182
183 if ($multi->performing) {
184 return;
185 }
186
187 curl_multi_remove_handle($multi->handle, $ch);
188 curl_setopt_array($ch, [
189 \CURLOPT_NOPROGRESS => true,
190 \CURLOPT_PROGRESSFUNCTION => null,
191 \CURLOPT_HEADERFUNCTION => null,
192 \CURLOPT_WRITEFUNCTION => null,
193 \CURLOPT_READFUNCTION => null,
194 \CURLOPT_INFILE => null,
195 ]);
196
197 if (!$multi->openHandles) {
198 // Schedule DNS cache eviction for the next request
199 $multi->dnsCache->evictions = $multi->dnsCache->evictions ?: $multi->dnsCache->removals;
200 $multi->dnsCache->removals = $multi->dnsCache->hostnames = [];
201 }
202 });
203 }
204
205 public function getInfo(?string $type = null): mixed
206 {
207 if (!$info = $this->finalInfo) {
208 $info = array_merge($this->info, curl_getinfo($this->handle));
209 $info['redirect_url'] = $this->info['redirect_url'] ?? null;
210
211 // workaround curl not subtracting the time offset for pushed responses
212 if (isset($this->info['url']) && $info['start_time'] / 1000 < $info['total_time']) {
213 $info['total_time'] -= $info['starttransfer_time'] ?: $info['total_time'];
214 $info['starttransfer_time'] = 0.0;
215 }
216
217 $info['debug'] ??= '';
218 rewind($this->debugBuffer);
219 if (fstat($this->debugBuffer)['size']) {
220 $info['debug'] .= stream_get_contents($this->debugBuffer);
221 rewind($this->debugBuffer);
222 ftruncate($this->debugBuffer, 0);
223 }
224 $this->info = array_merge($this->info, $info);
225 $waitFor = curl_getinfo($this->handle, \CURLINFO_PRIVATE);
226
227 if ('H' !== $waitFor[0] && 'C' !== $waitFor[0]) {
228 curl_setopt($this->handle, \CURLOPT_VERBOSE, false);
229 $this->finalInfo = $info;
230 }
231 }
232
233 return null !== $type ? $info[$type] ?? null : $info;
234 }
235
236 public function getContent(bool $throw = true): string
237 {
238 $performing = $this->multi->performing;
239 $this->multi->performing = $performing || '_0' === curl_getinfo($this->handle, \CURLINFO_PRIVATE);
240
241 try {
242 return $this->doGetContent($throw);
243 } finally {
244 $this->multi->performing = $performing;
245 }
246 }
247
248 public function __destruct()
249 {
250 try {
251 if (null === $this->timeout) {
252 return; // Unused pushed response
253 }
254
255 $this->doDestruct();
256 } finally {
257 if ($this->handle instanceof \CurlHandle) {
258 curl_setopt($this->handle, \CURLOPT_VERBOSE, false);
259 }
260 }
261 }
262
263 private static function schedule(self $response, array &$runningResponses): void
264 {
265 if (isset($runningResponses[$i = (int) $response->multi->handle])) {
266 $runningResponses[$i][1][$response->id] = $response;
267 } else {
268 $runningResponses[$i] = [$response->multi, [$response->id => $response]];
269 }
270
271 if ('_0' === curl_getinfo($response->handle, \CURLINFO_PRIVATE)) {
272 // Response already completed
273 $response->multi->handlesActivity[$response->id][] = null;
274 $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
275 }
276 }
277
278 /**
279 * @param CurlClientState $multi
280 */
281 private static function perform(ClientState $multi, ?array $responses = null): void
282 {
283 if ($multi->performing) {
284 if ($responses) {
285 $response = $responses[array_key_first($responses)];
286 $multi->handlesActivity[(int) $response->handle][] = null;
287 $multi->handlesActivity[(int) $response->handle][] = new TransportException(\sprintf('Userland callback cannot use the client nor the response while processing "%s".', curl_getinfo($response->handle, \CURLINFO_EFFECTIVE_URL)));
288 }
289
290 return;
291 }
292
293 try {
294 $multi->performing = true;
295 ++$multi->execCounter;
296 $active = 0;
297 while (\CURLM_CALL_MULTI_PERFORM === ($err = curl_multi_exec($multi->handle, $active))) {
298 }
299
300 if (\CURLM_OK !== $err) {
301 throw new TransportException(curl_multi_strerror($err));
302 }
303
304 while ($info = curl_multi_info_read($multi->handle)) {
305 if (\CURLMSG_DONE !== $info['msg']) {
306 continue;
307 }
308 $result = $info['result'];
309 $id = (int) $ch = $info['handle'];
310 $waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0';
311
312 if (isset($responses[$id]) && self::retryNtlmOnFreshConnection($multi, $ch, $responses[$id]->ntlmOriginKey, $result)) {
313 continue;
314 }
315
316 if (\in_array($result, [\CURLE_SEND_ERROR, \CURLE_RECV_ERROR, /* CURLE_HTTP2 */ 16, /* CURLE_HTTP2_STREAM */ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
317 curl_multi_remove_handle($multi->handle, $ch);
318 $waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
319 curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor);
320 curl_setopt($ch, \CURLOPT_FORBID_REUSE, true);
321
322 if (0 === curl_multi_add_handle($multi->handle, $ch)) {
323 continue;
324 }
325 }
326
327 if (\CURLE_RECV_ERROR === $result && 'H' === $waitFor[0] && 400 <= ($responses[(int) $ch]->info['http_code'] ?? 0)) {
328 $multi->handlesActivity[$id][] = new FirstChunk();
329 curl_setopt($ch, \CURLOPT_PRIVATE, 'C'.$waitFor[1]);
330 }
331
332 $multi->handlesActivity[$id][] = null;
333 $multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true)
334 || '_0' === $waitFor
335 || curl_getinfo($ch, \CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD)
336 || ('C' === $waitFor[0]
337 && 'OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 0' === curl_error($ch)
338 && -1.0 === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD)
339 && \in_array('close', array_map('strtolower', $responses[$id]->headers['connection'] ?? []), true)
340 )
341 ? null
342 : new TransportException(ucfirst(curl_error($ch) ?: curl_strerror($result)).\sprintf(' for "%s".', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
343 }
344 } finally {
345 $multi->performing = false;
346 }
347 }
348
349 /**
350 * @param CurlClientState $multi
351 */
352 private static function select(ClientState $multi, float $timeout): int
353 {
354 if ($multi->pauseExpiries) {
355 $now = hrtime(true) / 1E9;
356
357 foreach ($multi->pauseExpiries as $id => $pauseExpiry) {
358 if ($now < $pauseExpiry) {
359 $timeout = min($timeout, $pauseExpiry - $now);
360 break;
361 }
362
363 unset($multi->pauseExpiries[$id]);
364 curl_pause($multi->openHandles[$id][0], \CURLPAUSE_CONT);
365 curl_multi_add_handle($multi->handle, $multi->openHandles[$id][0]);
366 }
367 }
368
369 if (0 !== $selected = curl_multi_select($multi->handle, $timeout)) {
370 return $selected;
371 }
372
373 if ($multi->pauseExpiries && 0 < $timeout -= hrtime(true) / 1E9 - $now) {
374 usleep((int) (1E6 * $timeout));
375 }
376
377 return 0;
378 }
379
380 /**
381 * Parses header lines as curl yields them to us.
382 */
383 private static function parseHeaderLine($ch, string $data, array &$info, array &$headers, ?array $options, CurlClientState $multi, int $id, ?string &$location, ?callable $resolveRedirect, ?LoggerInterface $logger): int
384 {
385 if (!str_ends_with($data, "\r\n")) {
386 return 0;
387 }
388
389 $waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0';
390
391 if ('H' !== $waitFor[0]) {
392 return \strlen($data); // Ignore HTTP trailers
393 }
394
395 $statusCode = curl_getinfo($ch, \CURLINFO_RESPONSE_CODE);
396
397 if ($statusCode !== $info['http_code'] && !preg_match("#^HTTP/\d+(?:\.\d+)? {$statusCode}(?: |\r\n$)#", $data)) {
398 return \strlen($data); // Ignore headers from responses to CONNECT requests
399 }
400
401 if ("\r\n" !== $data) {
402 // Regular header line: add it to the list
403 self::addResponseHeaders([substr($data, 0, -2)], $info, $headers);
404
405 if (!str_starts_with($data, 'HTTP/')) {
406 if (0 === stripos($data, 'Location:')) {
407 $location = trim(substr($data, 9, -2));
408 }
409
410 return \strlen($data);
411 }
412
413 if (\function_exists('openssl_x509_read') && $certinfo = curl_getinfo($ch, \CURLINFO_CERTINFO)) {
414 $info['peer_certificate_chain'] = array_map('openssl_x509_read', array_column($certinfo, 'Cert'));
415 }
416
417 if (300 <= $info['http_code'] && $info['http_code'] < 400 && null !== $options) {
418 if (curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
419 curl_setopt($ch, \CURLOPT_FOLLOWLOCATION, false);
420 } elseif (303 === $info['http_code'] || ('POST' === $info['http_method'] && \in_array($info['http_code'], [301, 302], true))) {
421 curl_setopt($ch, \CURLOPT_POSTFIELDS, '');
422 }
423 }
424
425 return \strlen($data);
426 }
427
428 // End of headers: handle informational responses, redirects, etc.
429
430 if (200 > $statusCode) {
431 $multi->handlesActivity[$id][] = new InformationalChunk($statusCode, $headers);
432 $location = null;
433
434 return \strlen($data);
435 }
436
437 $info['redirect_url'] = null;
438
439 if (300 <= $statusCode && $statusCode < 400 && null !== $location && null !== $options) {
440 if ($noContent = 303 === $statusCode || ('POST' === $info['http_method'] && \in_array($statusCode, [301, 302], true))) {
441 $info['http_method'] = 'HEAD' === $info['http_method'] ? 'HEAD' : 'GET';
442 curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, $info['http_method']);
443 }
444
445 if (null === $info['redirect_url'] = $resolveRedirect($ch, $location, $noContent)) {
446 $options['max_redirects'] = curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT);
447 curl_setopt($ch, \CURLOPT_FOLLOWLOCATION, false);
448 curl_setopt($ch, \CURLOPT_MAXREDIRS, $options['max_redirects']);
449 }
450 }
451
452 if (401 === $statusCode && isset($options['auth_ntlm']) && 0 === strncasecmp($headers['www-authenticate'][0] ?? '', 'NTLM ', 5)) {
453 // Continue with NTLM auth
454 } elseif ($statusCode < 300 || 400 <= $statusCode || null === $location || null === $options || curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
455 // Headers and redirects completed, time to get the response's content
456 $multi->handlesActivity[$id][] = new FirstChunk();
457
458 if ('HEAD' === $info['http_method'] || \in_array($statusCode, [204, 304], true)) {
459 $waitFor = '_0'; // no content expected
460 $multi->handlesActivity[$id][] = null;
461 $multi->handlesActivity[$id][] = null;
462 } else {
463 $waitFor[0] = 'C'; // C = content
464 }
465
466 curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor);
467 } elseif (null !== $info['redirect_url'] && $logger) {
468 $logger->info(\sprintf('Redirecting: "%s %s"', $info['http_code'], $info['redirect_url']));
469 }
470
471 $location = null;
472
473 return \strlen($data);
474 }
475
476 /**
477 * Handles servers that do not persist NTLM authentication across requests on a reused
478 * TCP connection (e.g. IIS with authPersistNonNTLM=false). On such servers, libcurl
479 * still considers the pooled socket authenticated client-side and skips the handshake,
480 * but the server returns a fresh 401 + NTLM challenge that libcurl cannot pick up on
481 * the same request, so the caller sees an unauthenticated 401.
482 *
483 * The discriminator is CURLINFO_NUM_CONNECTS == 0: no new connection was opened for
484 * this request, so the socket came from the pool. A 401 + NTLM challenge on a brand
485 * new socket is the legitimate first leg of libcurl's in-request 3-way handshake and
486 * must NOT trigger this path.
487 *
488 * When detected, the deauthenticated socket is closed, the request is retried once on
489 * a fresh one, and the origin is recorded so subsequent requests to it skip the pool
490 * from the start.
491 */
492 private static function retryNtlmOnFreshConnection(CurlClientState $multi, \CurlHandle $ch, ?string $originKey, int $result): bool
493 {
494 if (null === $originKey
495 || \CURLE_OK !== $result
496 || 401 !== curl_getinfo($ch, \CURLINFO_RESPONSE_CODE)
497 || 0 === (curl_getinfo($ch, \CURLINFO_HTTPAUTH_AVAIL) & \CURLAUTH_NTLM)
498 || 0 !== curl_getinfo($ch, \CURLINFO_NUM_CONNECTS)
499 || isset($multi->ntlmRequiresFreshConnection[$originKey])
500 ) {
501 return false;
502 }
503
504 $multi->ntlmRequiresFreshConnection[$originKey] = true;
505 $multi->logger?->info(\sprintf('Discarding NTLM-deauthenticated connection to "%s" and retrying on a fresh one', $originKey));
506 curl_setopt($ch, \CURLOPT_FORBID_REUSE, true);
507 curl_multi_remove_handle($multi->handle, $ch);
508 curl_setopt($ch, \CURLOPT_FRESH_CONNECT, true);
509
510 return 0 === curl_multi_add_handle($multi->handle, $ch);
511 }
512 }