Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/Response/NativeResponse.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\Exception\TransportException;
17 use Symfony\Component\HttpClient\Internal\Canary;
18 use Symfony\Component\HttpClient\Internal\ClientState;
19 use Symfony\Component\HttpClient\Internal\NativeClientState;
20 use Symfony\Contracts\HttpClient\ResponseInterface;
21
22 /**
23 * @author Nicolas Grekas <[email protected]>
24 *
25 * @internal
26 */
27 final class NativeResponse implements ResponseInterface, StreamableInterface
28 {
29 use CommonResponseTrait;
30 use TransportResponseTrait;
31
32 private \Closure $resolver;
33 private ?\Closure $onProgress;
34 private ?int $remaining = null;
35
36 /**
37 * @var resource|null
38 */
39 private $buffer;
40
41 private float $pauseExpiry = 0.0;
42
43 /**
44 * @internal
45 *
46 * @param $context resource
47 */
48 public function __construct(
49 private NativeClientState $multi,
50 private $context,
51 private string $url,
52 array $options,
53 array &$info,
54 callable $resolver,
55 ?callable $onProgress,
56 ?LoggerInterface $logger,
57 ) {
58 $this->id = $id = (int) $context;
59 $this->logger = $logger;
60 $this->timeout = $options['timeout'];
61 $this->info = &$info;
62 $this->resolver = $resolver(...);
63 $this->onProgress = $onProgress ? $onProgress(...) : null;
64 $this->inflate = !isset($options['normalized_headers']['accept-encoding']);
65 $this->shouldBuffer = $options['buffer'] ?? true;
66
67 // Temporary resource to dechunk the response stream
68 $this->buffer = fopen('php://temp', 'w+');
69
70 $info['original_url'] = implode('', $info['url']);
71 $info['user_data'] = $options['user_data'];
72 $info['max_duration'] = $options['max_duration'];
73 ++$multi->responseCount;
74
75 $this->initializer = static fn (self $response) => null === $response->remaining;
76
77 $pauseExpiry = &$this->pauseExpiry;
78 $info['pause_handler'] = static function (float $duration) use (&$pauseExpiry) {
79 $pauseExpiry = 0 < $duration ? hrtime(true) / 1E9 + $duration : 0;
80 };
81
82 $this->canary = new Canary(static function () use ($multi, $id) {
83 if (null !== ($host = $multi->openHandles[$id][6] ?? null) && isset($multi->hosts[$host]) && 0 >= --$multi->hosts[$host]) {
84 unset($multi->hosts[$host]);
85 }
86 unset($multi->openHandles[$id], $multi->handlesActivity[$id]);
87 });
88 }
89
90 public function getInfo(?string $type = null): mixed
91 {
92 if (!$info = $this->finalInfo) {
93 $info = $this->info;
94 $info['url'] = implode('', $info['url']);
95 unset($info['size_body'], $info['request_header']);
96
97 if (null === $this->buffer) {
98 $this->finalInfo = $info;
99 }
100 }
101
102 return null !== $type ? $info[$type] ?? null : $info;
103 }
104
105 public function __destruct()
106 {
107 try {
108 $this->doDestruct();
109 } finally {
110 // Clear the DNS cache when all requests completed
111 if (0 >= --$this->multi->responseCount) {
112 $this->multi->responseCount = 0;
113 $this->multi->dnsCache = [];
114 }
115 }
116 }
117
118 private function open(): void
119 {
120 $url = $this->url;
121
122 set_error_handler(function ($type, $msg) use (&$url) {
123 if (\E_NOTICE !== $type || 'fopen(): Content-type not specified assuming application/x-www-form-urlencoded' !== $msg) {
124 throw new TransportException($msg);
125 }
126
127 $this->logger?->info(\sprintf('%s for "%s".', $msg, $url ?? $this->url));
128 });
129
130 try {
131 $this->info['start_time'] = microtime(true);
132
133 [$resolver, $url] = ($this->resolver)($this->multi);
134
135 while (true) {
136 $context = stream_context_get_options($this->context);
137
138 if ($proxy = $context['http']['proxy'] ?? null) {
139 $this->info['debug'] .= "* Establish HTTP proxy tunnel to {$proxy}\n";
140 $this->info['request_header'] = $url;
141 } else {
142 $this->info['debug'] .= "* Trying {$this->info['primary_ip']}...\n";
143 $this->info['request_header'] = $this->info['url']['path'].$this->info['url']['query'];
144 }
145
146 $this->info['request_header'] = \sprintf("> %s %s HTTP/%s \r\n", $context['http']['method'], $this->info['request_header'], $context['http']['protocol_version']);
147 $this->info['request_header'] .= implode("\r\n", $context['http']['header'])."\r\n\r\n";
148
149 if (\array_key_exists('peer_name', $context['ssl']) && null === $context['ssl']['peer_name']) {
150 unset($context['ssl']['peer_name']);
151 $this->context = stream_context_create([], ['options' => $context] + stream_context_get_params($this->context));
152 }
153
154 // Send request and follow redirects when needed
155 $this->handle = $h = fopen($url, 'r', false, $this->context);
156 self::addResponseHeaders(stream_get_meta_data($h)['wrapper_data'], $this->info, $this->headers, $this->info['debug']);
157 $url = $resolver($this->multi, $this->headers['location'][0] ?? null, $this->context);
158
159 if (null === $url) {
160 break;
161 }
162
163 $this->logger?->info(\sprintf('Redirecting: "%s %s"', $this->info['http_code'], $url ?? $this->url));
164 }
165 } catch (\Throwable $e) {
166 $this->close();
167 $this->multi->handlesActivity[$this->id][] = null;
168 $this->multi->handlesActivity[$this->id][] = $e;
169
170 return;
171 } finally {
172 $this->info['pretransfer_time'] = $this->info['total_time'] = microtime(true) - $this->info['start_time'];
173 restore_error_handler();
174 }
175
176 if (isset($context['ssl']['capture_peer_cert_chain']) && isset(($context = stream_context_get_options($this->context))['ssl']['peer_certificate_chain'])) {
177 $this->info['peer_certificate_chain'] = $context['ssl']['peer_certificate_chain'];
178 }
179
180 stream_set_blocking($h, false);
181 unset($this->context, $this->resolver);
182
183 // Create dechunk buffers
184 if (isset($this->headers['content-length'])) {
185 $this->remaining = (int) $this->headers['content-length'][0];
186 } elseif ('chunked' === ($this->headers['transfer-encoding'][0] ?? null)) {
187 stream_filter_append($this->buffer, 'dechunk', \STREAM_FILTER_WRITE);
188 $this->remaining = -1;
189 } else {
190 $this->remaining = -2;
191 }
192
193 $this->multi->handlesActivity[$this->id] = [new FirstChunk()];
194
195 if ('HEAD' === $context['http']['method'] || \in_array($this->info['http_code'], [204, 304], true)) {
196 $this->multi->handlesActivity[$this->id][] = null;
197 $this->multi->handlesActivity[$this->id][] = null;
198
199 return;
200 }
201
202 $host = parse_url($this->info['redirect_url'] ?? $this->url, \PHP_URL_HOST);
203 $this->multi->lastTimeout = null;
204 $this->multi->openHandles[$this->id] = [&$this->pauseExpiry, $h, $this->buffer, $this->onProgress, &$this->remaining, &$this->info, $host];
205 $this->multi->hosts[$host] = 1 + ($this->multi->hosts[$host] ?? 0);
206 }
207
208 private function close(): void
209 {
210 $this->canary->cancel();
211 $this->handle = $this->buffer = $this->inflate = $this->onProgress = null;
212 }
213
214 private static function schedule(self $response, array &$runningResponses): void
215 {
216 if (!isset($runningResponses[$i = $response->multi->id])) {
217 $runningResponses[$i] = [$response->multi, []];
218 }
219
220 $runningResponses[$i][1][$response->id] = $response;
221
222 if (null === $response->buffer) {
223 // Response already completed
224 $response->multi->handlesActivity[$response->id][] = null;
225 $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
226 }
227 }
228
229 /**
230 * @param NativeClientState $multi
231 */
232 private static function perform(ClientState $multi, ?array $responses = null): void
233 {
234 foreach ($multi->openHandles as $i => [$pauseExpiry, $h, $buffer, $onProgress]) {
235 if ($pauseExpiry) {
236 if (hrtime(true) / 1E9 < $pauseExpiry) {
237 continue;
238 }
239
240 $multi->openHandles[$i][0] = 0;
241 }
242
243 $hasActivity = false;
244 $remaining = &$multi->openHandles[$i][4];
245 $info = &$multi->openHandles[$i][5];
246 $e = null;
247
248 // Read incoming buffer and write it to the dechunk one
249 try {
250 if ($remaining && '' !== $data = (string) fread($h, 0 > $remaining ? 16372 : $remaining)) {
251 fwrite($buffer, $data);
252 $hasActivity = true;
253 $multi->sleep = false;
254
255 if (-1 !== $remaining) {
256 $remaining -= \strlen($data);
257 }
258 }
259 } catch (\Throwable $e) {
260 $hasActivity = $onProgress = false;
261 }
262
263 if (!$hasActivity) {
264 if ($onProgress) {
265 try {
266 // Notify the progress callback so that it can e.g. cancel
267 // the request if the stream is inactive for too long
268 $info['total_time'] = microtime(true) - $info['start_time'];
269 $onProgress();
270 } catch (\Throwable $e) {
271 // no-op
272 }
273 }
274 } elseif ('' !== $data = stream_get_contents($buffer, -1, 0)) {
275 rewind($buffer);
276 ftruncate($buffer, 0);
277
278 if (null === $e) {
279 $multi->handlesActivity[$i][] = $data;
280 }
281 }
282
283 if (null !== $e || !$remaining || feof($h)) {
284 // Stream completed
285 $info['total_time'] = microtime(true) - $info['start_time'];
286 $info['starttransfer_time'] = $info['starttransfer_time'] ?: $info['total_time'];
287
288 if ($onProgress) {
289 try {
290 $onProgress(-1);
291 } catch (\Throwable $e) {
292 // no-op
293 }
294 }
295
296 if (null === $e) {
297 if (0 < $remaining) {
298 $e = new TransportException(\sprintf('Transfer closed with %s bytes remaining to read.', $remaining));
299 } elseif (-1 === $remaining && fwrite($buffer, '-') && '' !== stream_get_contents($buffer, -1, 0)) {
300 $e = new TransportException('Transfer closed with outstanding data remaining from chunked response.');
301 }
302 }
303
304 $multi->handlesActivity[$i][] = null;
305 $multi->handlesActivity[$i][] = $e;
306 if (null !== ($host = $multi->openHandles[$i][6] ?? null) && isset($multi->hosts[$host]) && 0 >= --$multi->hosts[$host]) {
307 unset($multi->hosts[$host]);
308 }
309 unset($multi->openHandles[$i]);
310 $multi->sleep = false;
311 }
312 }
313
314 if (null === $responses) {
315 return;
316 }
317
318 $maxHosts = $multi->maxHostConnections;
319
320 foreach ($responses as $i => $response) {
321 if (null !== $response->remaining || null === $response->buffer) {
322 continue;
323 }
324
325 if ($response->pauseExpiry && hrtime(true) / 1E9 < $response->pauseExpiry) {
326 // Create empty open handles to tell we still have pending requests
327 $multi->openHandles[$i] = [\INF, null, null, null];
328 } elseif ($maxHosts && $maxHosts > ($multi->hosts[parse_url($response->url, \PHP_URL_HOST)] ?? 0)) {
329 // Open the next pending request - this is a blocking operation so we do only one of them
330 $response->open();
331 $multi->sleep = false;
332 self::perform($multi);
333 $maxHosts = 0;
334 }
335 }
336 }
337
338 /**
339 * @param NativeClientState $multi
340 */
341 private static function select(ClientState $multi, float $timeout): int
342 {
343 if (!$multi->sleep = !$multi->sleep) {
344 return -1;
345 }
346
347 $_ = $handles = [];
348 $now = null;
349
350 foreach ($multi->openHandles as [$pauseExpiry, $h]) {
351 if (null === $h) {
352 continue;
353 }
354
355 if ($pauseExpiry && ($now ??= hrtime(true) / 1E9) < $pauseExpiry) {
356 $timeout = min($timeout, $pauseExpiry - $now);
357 continue;
358 }
359
360 $handles[] = $h;
361 }
362
363 if (!$handles) {
364 usleep((int) (1E6 * $timeout));
365
366 return 0;
367 }
368
369 return stream_select($handles, $_, $_, (int) $timeout, (int) (1E6 * ($timeout - (int) $timeout)));
370 }
371 }