CurlResponse.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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\Chunk\InformationalChunk;
  14. use Symfony\Component\HttpClient\Exception\TransportException;
  15. use Symfony\Component\HttpClient\Internal\Canary;
  16. use Symfony\Component\HttpClient\Internal\ClientState;
  17. use Symfony\Component\HttpClient\Internal\CurlClientState;
  18. use Symfony\Contracts\HttpClient\ResponseInterface;
  19. /**
  20. * @author Nicolas Grekas <p@tchwork.com>
  21. *
  22. * @internal
  23. */
  24. final class CurlResponse implements ResponseInterface, StreamableInterface
  25. {
  26. use CommonResponseTrait {
  27. getContent as private doGetContent;
  28. }
  29. use TransportResponseTrait;
  30. private static $performing = false;
  31. private $multi;
  32. private $debugBuffer;
  33. /**
  34. * @param \CurlHandle|resource|string $ch
  35. *
  36. * @internal
  37. */
  38. public function __construct(CurlClientState $multi, $ch, array $options = null, LoggerInterface $logger = null, string $method = 'GET', callable $resolveRedirect = null, int $curlVersion = null)
  39. {
  40. $this->multi = $multi;
  41. if (\is_resource($ch) || $ch instanceof \CurlHandle) {
  42. $this->handle = $ch;
  43. $this->debugBuffer = fopen('php://temp', 'w+');
  44. if (0x074000 === $curlVersion) {
  45. 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.');
  46. } else {
  47. curl_setopt($ch, \CURLOPT_VERBOSE, true);
  48. curl_setopt($ch, \CURLOPT_STDERR, $this->debugBuffer);
  49. }
  50. } else {
  51. $this->info['url'] = $ch;
  52. $ch = $this->handle;
  53. }
  54. $this->id = $id = (int) $ch;
  55. $this->logger = $logger;
  56. $this->shouldBuffer = $options['buffer'] ?? true;
  57. $this->timeout = $options['timeout'] ?? null;
  58. $this->info['http_method'] = $method;
  59. $this->info['user_data'] = $options['user_data'] ?? null;
  60. $this->info['start_time'] = $this->info['start_time'] ?? microtime(true);
  61. $info = &$this->info;
  62. $headers = &$this->headers;
  63. $debugBuffer = $this->debugBuffer;
  64. if (!$info['response_headers']) {
  65. // Used to keep track of what we're waiting for
  66. curl_setopt($ch, \CURLOPT_PRIVATE, \in_array($method, ['GET', 'HEAD', 'OPTIONS', 'TRACE'], true) && 1.0 < (float) ($options['http_version'] ?? 1.1) ? 'H2' : 'H0'); // H = headers + retry counter
  67. }
  68. curl_setopt($ch, \CURLOPT_HEADERFUNCTION, static function ($ch, string $data) use (&$info, &$headers, $options, $multi, $id, &$location, $resolveRedirect, $logger): int {
  69. if (0 !== substr_compare($data, "\r\n", -2)) {
  70. return 0;
  71. }
  72. $len = 0;
  73. foreach (explode("\r\n", substr($data, 0, -2)) as $data) {
  74. $len += 2 + self::parseHeaderLine($ch, $data, $info, $headers, $options, $multi, $id, $location, $resolveRedirect, $logger);
  75. }
  76. return $len;
  77. });
  78. if (null === $options) {
  79. // Pushed response: buffer until requested
  80. curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int {
  81. $multi->handlesActivity[$id][] = $data;
  82. curl_pause($ch, \CURLPAUSE_RECV);
  83. return \strlen($data);
  84. });
  85. return;
  86. }
  87. $execCounter = $multi->execCounter;
  88. $this->info['pause_handler'] = static function (float $duration) use ($ch, $multi, $execCounter) {
  89. if (0 < $duration) {
  90. if ($execCounter === $multi->execCounter) {
  91. $multi->execCounter = !\is_float($execCounter) ? 1 + $execCounter : \PHP_INT_MIN;
  92. curl_multi_remove_handle($multi->handle, $ch);
  93. }
  94. $lastExpiry = end($multi->pauseExpiries);
  95. $multi->pauseExpiries[(int) $ch] = $duration += microtime(true);
  96. if (false !== $lastExpiry && $lastExpiry > $duration) {
  97. asort($multi->pauseExpiries);
  98. }
  99. curl_pause($ch, \CURLPAUSE_ALL);
  100. } else {
  101. unset($multi->pauseExpiries[(int) $ch]);
  102. curl_pause($ch, \CURLPAUSE_CONT);
  103. curl_multi_add_handle($multi->handle, $ch);
  104. }
  105. };
  106. $this->inflate = !isset($options['normalized_headers']['accept-encoding']);
  107. curl_pause($ch, \CURLPAUSE_CONT);
  108. if ($onProgress = $options['on_progress']) {
  109. $url = isset($info['url']) ? ['url' => $info['url']] : [];
  110. curl_setopt($ch, \CURLOPT_NOPROGRESS, false);
  111. curl_setopt($ch, \CURLOPT_PROGRESSFUNCTION, static function ($ch, $dlSize, $dlNow) use ($onProgress, &$info, $url, $multi, $debugBuffer) {
  112. try {
  113. rewind($debugBuffer);
  114. $debug = ['debug' => stream_get_contents($debugBuffer)];
  115. $onProgress($dlNow, $dlSize, $url + curl_getinfo($ch) + $info + $debug);
  116. } catch (\Throwable $e) {
  117. $multi->handlesActivity[(int) $ch][] = null;
  118. $multi->handlesActivity[(int) $ch][] = $e;
  119. return 1; // Abort the request
  120. }
  121. return null;
  122. });
  123. }
  124. curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int {
  125. if ('H' === (curl_getinfo($ch, \CURLINFO_PRIVATE)[0] ?? null)) {
  126. $multi->handlesActivity[$id][] = null;
  127. $multi->handlesActivity[$id][] = new TransportException(sprintf('Unsupported protocol for "%s"', curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
  128. return 0;
  129. }
  130. curl_setopt($ch, \CURLOPT_WRITEFUNCTION, static function ($ch, string $data) use ($multi, $id): int {
  131. $multi->handlesActivity[$id][] = $data;
  132. return \strlen($data);
  133. });
  134. $multi->handlesActivity[$id][] = $data;
  135. return \strlen($data);
  136. });
  137. $this->initializer = static function (self $response) {
  138. $waitFor = curl_getinfo($ch = $response->handle, \CURLINFO_PRIVATE);
  139. return 'H' === $waitFor[0];
  140. };
  141. // Schedule the request in a non-blocking way
  142. $multi->openHandles[$id] = [$ch, $options];
  143. curl_multi_add_handle($multi->handle, $ch);
  144. $this->canary = new Canary(static function () use ($ch, $multi, $id) {
  145. unset($multi->pauseExpiries[$id], $multi->openHandles[$id], $multi->handlesActivity[$id]);
  146. curl_setopt($ch, \CURLOPT_PRIVATE, '_0');
  147. if (self::$performing) {
  148. return;
  149. }
  150. curl_multi_remove_handle($multi->handle, $ch);
  151. curl_setopt_array($ch, [
  152. \CURLOPT_NOPROGRESS => true,
  153. \CURLOPT_PROGRESSFUNCTION => null,
  154. \CURLOPT_HEADERFUNCTION => null,
  155. \CURLOPT_WRITEFUNCTION => null,
  156. \CURLOPT_READFUNCTION => null,
  157. \CURLOPT_INFILE => null,
  158. ]);
  159. if (!$multi->openHandles) {
  160. // Schedule DNS cache eviction for the next request
  161. $multi->dnsCache->evictions = $multi->dnsCache->evictions ?: $multi->dnsCache->removals;
  162. $multi->dnsCache->removals = $multi->dnsCache->hostnames = [];
  163. }
  164. });
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function getInfo(string $type = null)
  170. {
  171. if (!$info = $this->finalInfo) {
  172. $info = array_merge($this->info, curl_getinfo($this->handle));
  173. $info['url'] = $this->info['url'] ?? $info['url'];
  174. $info['redirect_url'] = $this->info['redirect_url'] ?? null;
  175. // workaround curl not subtracting the time offset for pushed responses
  176. if (isset($this->info['url']) && $info['start_time'] / 1000 < $info['total_time']) {
  177. $info['total_time'] -= $info['starttransfer_time'] ?: $info['total_time'];
  178. $info['starttransfer_time'] = 0.0;
  179. }
  180. rewind($this->debugBuffer);
  181. $info['debug'] = stream_get_contents($this->debugBuffer);
  182. $waitFor = curl_getinfo($this->handle, \CURLINFO_PRIVATE);
  183. if ('H' !== $waitFor[0] && 'C' !== $waitFor[0]) {
  184. curl_setopt($this->handle, \CURLOPT_VERBOSE, false);
  185. rewind($this->debugBuffer);
  186. ftruncate($this->debugBuffer, 0);
  187. $this->finalInfo = $info;
  188. }
  189. }
  190. return null !== $type ? $info[$type] ?? null : $info;
  191. }
  192. /**
  193. * {@inheritdoc}
  194. */
  195. public function getContent(bool $throw = true): string
  196. {
  197. $performing = self::$performing;
  198. self::$performing = $performing || '_0' === curl_getinfo($this->handle, \CURLINFO_PRIVATE);
  199. try {
  200. return $this->doGetContent($throw);
  201. } finally {
  202. self::$performing = $performing;
  203. }
  204. }
  205. public function __destruct()
  206. {
  207. curl_setopt($this->handle, \CURLOPT_VERBOSE, false);
  208. if (null === $this->timeout) {
  209. return; // Unused pushed response
  210. }
  211. $this->doDestruct();
  212. }
  213. /**
  214. * {@inheritdoc}
  215. */
  216. private static function schedule(self $response, array &$runningResponses): void
  217. {
  218. if (isset($runningResponses[$i = (int) $response->multi->handle])) {
  219. $runningResponses[$i][1][$response->id] = $response;
  220. } else {
  221. $runningResponses[$i] = [$response->multi, [$response->id => $response]];
  222. }
  223. if ('_0' === curl_getinfo($ch = $response->handle, \CURLINFO_PRIVATE)) {
  224. // Response already completed
  225. $response->multi->handlesActivity[$response->id][] = null;
  226. $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
  227. }
  228. }
  229. /**
  230. * {@inheritdoc}
  231. *
  232. * @param CurlClientState $multi
  233. */
  234. private static function perform(ClientState $multi, array &$responses = null): void
  235. {
  236. if (self::$performing) {
  237. if ($responses) {
  238. $response = current($responses);
  239. $multi->handlesActivity[(int) $response->handle][] = null;
  240. $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)));
  241. }
  242. return;
  243. }
  244. try {
  245. self::$performing = true;
  246. ++$multi->execCounter;
  247. $active = 0;
  248. while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($multi->handle, $active));
  249. while ($info = curl_multi_info_read($multi->handle)) {
  250. $result = $info['result'];
  251. $id = (int) $ch = $info['handle'];
  252. $waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0';
  253. if (\in_array($result, [\CURLE_SEND_ERROR, \CURLE_RECV_ERROR, /*CURLE_HTTP2*/ 16, /*CURLE_HTTP2_STREAM*/ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
  254. curl_multi_remove_handle($multi->handle, $ch);
  255. $waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
  256. curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor);
  257. curl_setopt($ch, \CURLOPT_FORBID_REUSE, true);
  258. if (0 === curl_multi_add_handle($multi->handle, $ch)) {
  259. continue;
  260. }
  261. }
  262. $multi->handlesActivity[$id][] = null;
  263. $multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch, \CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(sprintf('%s for "%s".', curl_strerror($result), curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
  264. }
  265. } finally {
  266. self::$performing = false;
  267. }
  268. }
  269. /**
  270. * {@inheritdoc}
  271. *
  272. * @param CurlClientState $multi
  273. */
  274. private static function select(ClientState $multi, float $timeout): int
  275. {
  276. if (\PHP_VERSION_ID < 70211) {
  277. // workaround https://bugs.php.net/76480
  278. $timeout = min($timeout, 0.01);
  279. }
  280. if ($multi->pauseExpiries) {
  281. $now = microtime(true);
  282. foreach ($multi->pauseExpiries as $id => $pauseExpiry) {
  283. if ($now < $pauseExpiry) {
  284. $timeout = min($timeout, $pauseExpiry - $now);
  285. break;
  286. }
  287. unset($multi->pauseExpiries[$id]);
  288. curl_pause($multi->openHandles[$id][0], \CURLPAUSE_CONT);
  289. curl_multi_add_handle($multi->handle, $multi->openHandles[$id][0]);
  290. }
  291. }
  292. if (0 !== $selected = curl_multi_select($multi->handle, $timeout)) {
  293. return $selected;
  294. }
  295. if ($multi->pauseExpiries && 0 < $timeout -= microtime(true) - $now) {
  296. usleep(1E6 * $timeout);
  297. }
  298. return 0;
  299. }
  300. /**
  301. * Parses header lines as curl yields them to us.
  302. */
  303. private static function parseHeaderLine($ch, string $data, array &$info, array &$headers, ?array $options, CurlClientState $multi, int $id, ?string &$location, ?callable $resolveRedirect, ?LoggerInterface $logger, &$content = null): int
  304. {
  305. $waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0';
  306. if ('H' !== $waitFor[0]) {
  307. return \strlen($data); // Ignore HTTP trailers
  308. }
  309. if ('' !== $data) {
  310. try {
  311. // Regular header line: add it to the list
  312. self::addResponseHeaders([$data], $info, $headers);
  313. } catch (TransportException $e) {
  314. $multi->handlesActivity[$id][] = null;
  315. $multi->handlesActivity[$id][] = $e;
  316. return \strlen($data);
  317. }
  318. if (0 !== strpos($data, 'HTTP/')) {
  319. if (0 === stripos($data, 'Location:')) {
  320. $location = trim(substr($data, 9));
  321. }
  322. return \strlen($data);
  323. }
  324. if (\function_exists('openssl_x509_read') && $certinfo = curl_getinfo($ch, \CURLINFO_CERTINFO)) {
  325. $info['peer_certificate_chain'] = array_map('openssl_x509_read', array_column($certinfo, 'Cert'));
  326. }
  327. if (300 <= $info['http_code'] && $info['http_code'] < 400) {
  328. if (curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  329. curl_setopt($ch, \CURLOPT_FOLLOWLOCATION, false);
  330. } elseif (303 === $info['http_code'] || ('POST' === $info['http_method'] && \in_array($info['http_code'], [301, 302], true))) {
  331. $info['http_method'] = 'HEAD' === $info['http_method'] ? 'HEAD' : 'GET';
  332. curl_setopt($ch, \CURLOPT_POSTFIELDS, '');
  333. }
  334. }
  335. return \strlen($data);
  336. }
  337. // End of headers: handle informational responses, redirects, etc.
  338. if (200 > $statusCode = curl_getinfo($ch, \CURLINFO_RESPONSE_CODE)) {
  339. $multi->handlesActivity[$id][] = new InformationalChunk($statusCode, $headers);
  340. $location = null;
  341. return \strlen($data);
  342. }
  343. $info['redirect_url'] = null;
  344. if (300 <= $statusCode && $statusCode < 400 && null !== $location) {
  345. if (null === $info['redirect_url'] = $resolveRedirect($ch, $location)) {
  346. $options['max_redirects'] = curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT);
  347. curl_setopt($ch, \CURLOPT_FOLLOWLOCATION, false);
  348. curl_setopt($ch, \CURLOPT_MAXREDIRS, $options['max_redirects']);
  349. } else {
  350. $url = parse_url($location ?? ':');
  351. if (isset($url['host']) && null !== $ip = $multi->dnsCache->hostnames[$url['host'] = strtolower($url['host'])] ?? null) {
  352. // Populate DNS cache for redirects if needed
  353. $port = $url['port'] ?? ('http' === ($url['scheme'] ?? parse_url(curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL), \PHP_URL_SCHEME)) ? 80 : 443);
  354. curl_setopt($ch, \CURLOPT_RESOLVE, ["{$url['host']}:$port:$ip"]);
  355. $multi->dnsCache->removals["-{$url['host']}:$port"] = "-{$url['host']}:$port";
  356. }
  357. }
  358. }
  359. if (401 === $statusCode && isset($options['auth_ntlm']) && 0 === strncasecmp($headers['www-authenticate'][0] ?? '', 'NTLM ', 5)) {
  360. // Continue with NTLM auth
  361. } elseif ($statusCode < 300 || 400 <= $statusCode || null === $location || curl_getinfo($ch, \CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  362. // Headers and redirects completed, time to get the response's content
  363. $multi->handlesActivity[$id][] = new FirstChunk();
  364. if ('HEAD' === $info['http_method'] || \in_array($statusCode, [204, 304], true)) {
  365. $waitFor = '_0'; // no content expected
  366. $multi->handlesActivity[$id][] = null;
  367. $multi->handlesActivity[$id][] = null;
  368. } else {
  369. $waitFor[0] = 'C'; // C = content
  370. }
  371. curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor);
  372. } elseif (null !== $info['redirect_url'] && $logger) {
  373. $logger->info(sprintf('Redirecting: "%s %s"', $info['http_code'], $info['redirect_url']));
  374. }
  375. $location = null;
  376. return \strlen($data);
  377. }
  378. }