NativeResponse.php 13 KB

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