CurlResponse.php 19 KB

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