CurlResponse.php 19 KB

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