CurlHttpClient.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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;
  11. use Psr\Log\LoggerAwareInterface;
  12. use Psr\Log\LoggerAwareTrait;
  13. use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
  14. use Symfony\Component\HttpClient\Exception\TransportException;
  15. use Symfony\Component\HttpClient\Internal\CurlClientState;
  16. use Symfony\Component\HttpClient\Internal\PushedResponse;
  17. use Symfony\Component\HttpClient\Response\CurlResponse;
  18. use Symfony\Component\HttpClient\Response\ResponseStream;
  19. use Symfony\Contracts\HttpClient\HttpClientInterface;
  20. use Symfony\Contracts\HttpClient\ResponseInterface;
  21. use Symfony\Contracts\HttpClient\ResponseStreamInterface;
  22. use Symfony\Contracts\Service\ResetInterface;
  23. /**
  24. * A performant implementation of the HttpClientInterface contracts based on the curl extension.
  25. *
  26. * This provides fully concurrent HTTP requests, with transparent
  27. * HTTP/2 push when a curl version that supports it is installed.
  28. *
  29. * @author Nicolas Grekas <p@tchwork.com>
  30. */
  31. final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface, ResetInterface
  32. {
  33. use HttpClientTrait;
  34. use LoggerAwareTrait;
  35. private $defaultOptions = self::OPTIONS_DEFAULTS + [
  36. 'auth_ntlm' => null, // array|string - an array containing the username as first value, and optionally the
  37. // password as the second one; or string like username:password - enabling NTLM auth
  38. 'extra' => [
  39. 'curl' => [], // A list of extra curl options indexed by their corresponding CURLOPT_*
  40. ],
  41. ];
  42. /**
  43. * An internal object to share state between the client and its responses.
  44. *
  45. * @var CurlClientState
  46. */
  47. private $multi;
  48. private static $curlVersion;
  49. /**
  50. * @param array $defaultOptions Default request's options
  51. * @param int $maxHostConnections The maximum number of connections to a single host
  52. * @param int $maxPendingPushes The maximum number of pushed responses to accept in the queue
  53. *
  54. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  55. */
  56. public function __construct(array $defaultOptions = [], int $maxHostConnections = 6, int $maxPendingPushes = 50)
  57. {
  58. if (!\extension_loaded('curl')) {
  59. throw new \LogicException('You cannot use the "Symfony\Component\HttpClient\CurlHttpClient" as the "curl" extension is not installed.');
  60. }
  61. $this->defaultOptions['buffer'] = $this->defaultOptions['buffer'] ?? \Closure::fromCallable([__CLASS__, 'shouldBuffer']);
  62. if ($defaultOptions) {
  63. [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
  64. }
  65. $this->multi = new CurlClientState();
  66. self::$curlVersion = self::$curlVersion ?? curl_version();
  67. // Don't enable HTTP/1.1 pipelining: it forces responses to be sent in order
  68. if (\defined('CURLPIPE_MULTIPLEX')) {
  69. curl_multi_setopt($this->multi->handle, \CURLMOPT_PIPELINING, \CURLPIPE_MULTIPLEX);
  70. }
  71. if (\defined('CURLMOPT_MAX_HOST_CONNECTIONS')) {
  72. $maxHostConnections = curl_multi_setopt($this->multi->handle, \CURLMOPT_MAX_HOST_CONNECTIONS, 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX) ? 0 : $maxHostConnections;
  73. }
  74. if (\defined('CURLMOPT_MAXCONNECTS') && 0 < $maxHostConnections) {
  75. curl_multi_setopt($this->multi->handle, \CURLMOPT_MAXCONNECTS, $maxHostConnections);
  76. }
  77. // Skip configuring HTTP/2 push when it's unsupported or buggy, see https://bugs.php.net/77535
  78. if (0 >= $maxPendingPushes || \PHP_VERSION_ID < 70217 || (\PHP_VERSION_ID >= 70300 && \PHP_VERSION_ID < 70304)) {
  79. return;
  80. }
  81. // HTTP/2 push crashes before curl 7.61
  82. if (!\defined('CURLMOPT_PUSHFUNCTION') || 0x073d00 > self::$curlVersion['version_number'] || !(\CURL_VERSION_HTTP2 & self::$curlVersion['features'])) {
  83. return;
  84. }
  85. curl_multi_setopt($this->multi->handle, \CURLMOPT_PUSHFUNCTION, function ($parent, $pushed, array $requestHeaders) use ($maxPendingPushes) {
  86. return $this->handlePush($parent, $pushed, $requestHeaders, $maxPendingPushes);
  87. });
  88. }
  89. /**
  90. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  91. *
  92. * {@inheritdoc}
  93. */
  94. public function request(string $method, string $url, array $options = []): ResponseInterface
  95. {
  96. [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
  97. $scheme = $url['scheme'];
  98. $authority = $url['authority'];
  99. $host = parse_url($authority, \PHP_URL_HOST);
  100. $url = implode('', $url);
  101. if (!isset($options['normalized_headers']['user-agent'])) {
  102. $options['headers'][] = 'User-Agent: Symfony HttpClient/Curl';
  103. }
  104. $curlopts = [
  105. \CURLOPT_URL => $url,
  106. \CURLOPT_TCP_NODELAY => true,
  107. \CURLOPT_PROTOCOLS => \CURLPROTO_HTTP | \CURLPROTO_HTTPS,
  108. \CURLOPT_REDIR_PROTOCOLS => \CURLPROTO_HTTP | \CURLPROTO_HTTPS,
  109. \CURLOPT_FOLLOWLOCATION => true,
  110. \CURLOPT_MAXREDIRS => 0 < $options['max_redirects'] ? $options['max_redirects'] : 0,
  111. \CURLOPT_COOKIEFILE => '', // Keep track of cookies during redirects
  112. \CURLOPT_TIMEOUT => 0,
  113. \CURLOPT_PROXY => $options['proxy'],
  114. \CURLOPT_NOPROXY => $options['no_proxy'] ?? $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '',
  115. \CURLOPT_SSL_VERIFYPEER => $options['verify_peer'],
  116. \CURLOPT_SSL_VERIFYHOST => $options['verify_host'] ? 2 : 0,
  117. \CURLOPT_CAINFO => $options['cafile'],
  118. \CURLOPT_CAPATH => $options['capath'],
  119. \CURLOPT_SSL_CIPHER_LIST => $options['ciphers'],
  120. \CURLOPT_SSLCERT => $options['local_cert'],
  121. \CURLOPT_SSLKEY => $options['local_pk'],
  122. \CURLOPT_KEYPASSWD => $options['passphrase'],
  123. \CURLOPT_CERTINFO => $options['capture_peer_cert_chain'],
  124. ];
  125. if (1.0 === (float) $options['http_version']) {
  126. $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
  127. } elseif (1.1 === (float) $options['http_version']) {
  128. $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
  129. } elseif (\defined('CURL_VERSION_HTTP2') && (\CURL_VERSION_HTTP2 & self::$curlVersion['features']) && ('https:' === $scheme || 2.0 === (float) $options['http_version'])) {
  130. $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
  131. }
  132. if (isset($options['auth_ntlm'])) {
  133. $curlopts[\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM;
  134. $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
  135. if (\is_array($options['auth_ntlm'])) {
  136. $count = \count($options['auth_ntlm']);
  137. if ($count <= 0 || $count > 2) {
  138. throw new InvalidArgumentException(sprintf('Option "auth_ntlm" must contain 1 or 2 elements, %d given.', $count));
  139. }
  140. $options['auth_ntlm'] = implode(':', $options['auth_ntlm']);
  141. }
  142. if (!\is_string($options['auth_ntlm'])) {
  143. throw new InvalidArgumentException(sprintf('Option "auth_ntlm" must be a string or an array, "%s" given.', get_debug_type($options['auth_ntlm'])));
  144. }
  145. $curlopts[\CURLOPT_USERPWD] = $options['auth_ntlm'];
  146. }
  147. if (!\ZEND_THREAD_SAFE) {
  148. $curlopts[\CURLOPT_DNS_USE_GLOBAL_CACHE] = false;
  149. }
  150. if (\defined('CURLOPT_HEADEROPT') && \defined('CURLHEADER_SEPARATE')) {
  151. $curlopts[\CURLOPT_HEADEROPT] = \CURLHEADER_SEPARATE;
  152. }
  153. // curl's resolve feature varies by host:port but ours varies by host only, let's handle this with our own DNS map
  154. if (isset($this->multi->dnsCache->hostnames[$host])) {
  155. $options['resolve'] += [$host => $this->multi->dnsCache->hostnames[$host]];
  156. }
  157. if ($options['resolve'] || $this->multi->dnsCache->evictions) {
  158. // First reset any old DNS cache entries then add the new ones
  159. $resolve = $this->multi->dnsCache->evictions;
  160. $this->multi->dnsCache->evictions = [];
  161. $port = parse_url($authority, \PHP_URL_PORT) ?: ('http:' === $scheme ? 80 : 443);
  162. if ($resolve && 0x072a00 > self::$curlVersion['version_number']) {
  163. // DNS cache removals require curl 7.42 or higher
  164. // On lower versions, we have to create a new multi handle
  165. curl_multi_close($this->multi->handle);
  166. $this->multi->handle = (new self())->multi->handle;
  167. }
  168. foreach ($options['resolve'] as $host => $ip) {
  169. $resolve[] = null === $ip ? "-$host:$port" : "$host:$port:$ip";
  170. $this->multi->dnsCache->hostnames[$host] = $ip;
  171. $this->multi->dnsCache->removals["-$host:$port"] = "-$host:$port";
  172. }
  173. $curlopts[\CURLOPT_RESOLVE] = $resolve;
  174. }
  175. if ('POST' === $method) {
  176. // Use CURLOPT_POST to have browser-like POST-to-GET redirects for 301, 302 and 303
  177. $curlopts[\CURLOPT_POST] = true;
  178. } elseif ('HEAD' === $method) {
  179. $curlopts[\CURLOPT_NOBODY] = true;
  180. } else {
  181. $curlopts[\CURLOPT_CUSTOMREQUEST] = $method;
  182. }
  183. if ('\\' !== \DIRECTORY_SEPARATOR && $options['timeout'] < 1) {
  184. $curlopts[\CURLOPT_NOSIGNAL] = true;
  185. }
  186. if (\extension_loaded('zlib') && !isset($options['normalized_headers']['accept-encoding'])) {
  187. $options['headers'][] = 'Accept-Encoding: gzip'; // Expose only one encoding, some servers mess up when more are provided
  188. }
  189. foreach ($options['headers'] as $header) {
  190. if (':' === $header[-2] && \strlen($header) - 2 === strpos($header, ': ')) {
  191. // curl requires a special syntax to send empty headers
  192. $curlopts[\CURLOPT_HTTPHEADER][] = substr_replace($header, ';', -2);
  193. } else {
  194. $curlopts[\CURLOPT_HTTPHEADER][] = $header;
  195. }
  196. }
  197. // Prevent curl from sending its default Accept and Expect headers
  198. foreach (['accept', 'expect'] as $header) {
  199. if (!isset($options['normalized_headers'][$header][0])) {
  200. $curlopts[\CURLOPT_HTTPHEADER][] = $header.':';
  201. }
  202. }
  203. if (!\is_string($body = $options['body'])) {
  204. if (\is_resource($body)) {
  205. $curlopts[\CURLOPT_INFILE] = $body;
  206. } else {
  207. $eof = false;
  208. $buffer = '';
  209. $curlopts[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body, &$buffer, &$eof) {
  210. return self::readRequestBody($length, $body, $buffer, $eof);
  211. };
  212. }
  213. if (isset($options['normalized_headers']['content-length'][0])) {
  214. $curlopts[\CURLOPT_INFILESIZE] = substr($options['normalized_headers']['content-length'][0], \strlen('Content-Length: '));
  215. } elseif (!isset($options['normalized_headers']['transfer-encoding'])) {
  216. $curlopts[\CURLOPT_HTTPHEADER][] = 'Transfer-Encoding: chunked'; // Enable chunked request bodies
  217. }
  218. if ('POST' !== $method) {
  219. $curlopts[\CURLOPT_UPLOAD] = true;
  220. }
  221. } elseif ('' !== $body || 'POST' === $method) {
  222. $curlopts[\CURLOPT_POSTFIELDS] = $body;
  223. }
  224. if ($options['peer_fingerprint']) {
  225. if (!isset($options['peer_fingerprint']['pin-sha256'])) {
  226. throw new TransportException(__CLASS__.' supports only "pin-sha256" fingerprints.');
  227. }
  228. $curlopts[\CURLOPT_PINNEDPUBLICKEY] = 'sha256//'.implode(';sha256//', $options['peer_fingerprint']['pin-sha256']);
  229. }
  230. if ($options['bindto']) {
  231. if (file_exists($options['bindto'])) {
  232. $curlopts[\CURLOPT_UNIX_SOCKET_PATH] = $options['bindto'];
  233. } elseif (0 !== strpos($options['bindto'], 'if!') && preg_match('/^(.*):(\d+)$/', $options['bindto'], $matches)) {
  234. $curlopts[\CURLOPT_INTERFACE] = $matches[1];
  235. $curlopts[\CURLOPT_LOCALPORT] = $matches[2];
  236. } else {
  237. $curlopts[\CURLOPT_INTERFACE] = $options['bindto'];
  238. }
  239. }
  240. if (0 < $options['max_duration']) {
  241. $curlopts[\CURLOPT_TIMEOUT_MS] = 1000 * $options['max_duration'];
  242. }
  243. if (!empty($options['extra']['curl']) && \is_array($options['extra']['curl'])) {
  244. $this->validateExtraCurlOptions($options['extra']['curl']);
  245. $curlopts += $options['extra']['curl'];
  246. }
  247. if ($pushedResponse = $this->multi->pushedResponses[$url] ?? null) {
  248. unset($this->multi->pushedResponses[$url]);
  249. if (self::acceptPushForRequest($method, $options, $pushedResponse)) {
  250. $this->logger && $this->logger->debug(sprintf('Accepting pushed response: "%s %s"', $method, $url));
  251. // Reinitialize the pushed response with request's options
  252. $ch = $pushedResponse->handle;
  253. $pushedResponse = $pushedResponse->response;
  254. $pushedResponse->__construct($this->multi, $url, $options, $this->logger);
  255. } else {
  256. $this->logger && $this->logger->debug(sprintf('Rejecting pushed response: "%s"', $url));
  257. $pushedResponse = null;
  258. }
  259. }
  260. if (!$pushedResponse) {
  261. $ch = curl_init();
  262. $this->logger && $this->logger->info(sprintf('Request: "%s %s"', $method, $url));
  263. }
  264. foreach ($curlopts as $opt => $value) {
  265. if (null !== $value && !curl_setopt($ch, $opt, $value) && \CURLOPT_CERTINFO !== $opt) {
  266. $constantName = $this->findConstantName($opt);
  267. throw new TransportException(sprintf('Curl option "%s" is not supported.', $constantName ?? $opt));
  268. }
  269. }
  270. return $pushedResponse ?? new CurlResponse($this->multi, $ch, $options, $this->logger, $method, self::createRedirectResolver($options, $host), self::$curlVersion['version_number']);
  271. }
  272. /**
  273. * {@inheritdoc}
  274. */
  275. public function stream($responses, float $timeout = null): ResponseStreamInterface
  276. {
  277. if ($responses instanceof CurlResponse) {
  278. $responses = [$responses];
  279. } elseif (!is_iterable($responses)) {
  280. throw new \TypeError(sprintf('"%s()" expects parameter 1 to be an iterable of CurlResponse objects, "%s" given.', __METHOD__, get_debug_type($responses)));
  281. }
  282. if (\is_resource($this->multi->handle) || $this->multi->handle instanceof \CurlMultiHandle) {
  283. $active = 0;
  284. while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active));
  285. }
  286. return new ResponseStream(CurlResponse::stream($responses, $timeout));
  287. }
  288. public function reset()
  289. {
  290. if ($this->logger) {
  291. foreach ($this->multi->pushedResponses as $url => $response) {
  292. $this->logger->debug(sprintf('Unused pushed response: "%s"', $url));
  293. }
  294. }
  295. $this->multi->pushedResponses = [];
  296. $this->multi->dnsCache->evictions = $this->multi->dnsCache->evictions ?: $this->multi->dnsCache->removals;
  297. $this->multi->dnsCache->removals = $this->multi->dnsCache->hostnames = [];
  298. if (\is_resource($this->multi->handle) || $this->multi->handle instanceof \CurlMultiHandle) {
  299. if (\defined('CURLMOPT_PUSHFUNCTION')) {
  300. curl_multi_setopt($this->multi->handle, \CURLMOPT_PUSHFUNCTION, null);
  301. }
  302. $active = 0;
  303. while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active));
  304. }
  305. foreach ($this->multi->openHandles as [$ch]) {
  306. if (\is_resource($ch) || $ch instanceof \CurlHandle) {
  307. curl_setopt($ch, \CURLOPT_VERBOSE, false);
  308. }
  309. }
  310. }
  311. public function __sleep()
  312. {
  313. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  314. }
  315. public function __wakeup()
  316. {
  317. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  318. }
  319. public function __destruct()
  320. {
  321. $this->reset();
  322. }
  323. private function handlePush($parent, $pushed, array $requestHeaders, int $maxPendingPushes): int
  324. {
  325. $headers = [];
  326. $origin = curl_getinfo($parent, \CURLINFO_EFFECTIVE_URL);
  327. foreach ($requestHeaders as $h) {
  328. if (false !== $i = strpos($h, ':', 1)) {
  329. $headers[substr($h, 0, $i)][] = substr($h, 1 + $i);
  330. }
  331. }
  332. if (!isset($headers[':method']) || !isset($headers[':scheme']) || !isset($headers[':authority']) || !isset($headers[':path'])) {
  333. $this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": pushed headers are invalid', $origin));
  334. return \CURL_PUSH_DENY;
  335. }
  336. $url = $headers[':scheme'][0].'://'.$headers[':authority'][0];
  337. // curl before 7.65 doesn't validate the pushed ":authority" header,
  338. // but this is a MUST in the HTTP/2 RFC; let's restrict pushes to the original host,
  339. // ignoring domains mentioned as alt-name in the certificate for now (same as curl).
  340. if (0 !== strpos($origin, $url.'/')) {
  341. $this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url));
  342. return \CURL_PUSH_DENY;
  343. }
  344. if ($maxPendingPushes <= \count($this->multi->pushedResponses)) {
  345. $fifoUrl = key($this->multi->pushedResponses);
  346. unset($this->multi->pushedResponses[$fifoUrl]);
  347. $this->logger && $this->logger->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
  348. }
  349. $url .= $headers[':path'][0];
  350. $this->logger && $this->logger->debug(sprintf('Queueing pushed response: "%s"', $url));
  351. $this->multi->pushedResponses[$url] = new PushedResponse(new CurlResponse($this->multi, $pushed), $headers, $this->multi->openHandles[(int) $parent][1] ?? [], $pushed);
  352. return \CURL_PUSH_OK;
  353. }
  354. /**
  355. * Accepts pushed responses only if their headers related to authentication match the request.
  356. */
  357. private static function acceptPushForRequest(string $method, array $options, PushedResponse $pushedResponse): bool
  358. {
  359. if ('' !== $options['body'] || $method !== $pushedResponse->requestHeaders[':method'][0]) {
  360. return false;
  361. }
  362. foreach (['proxy', 'no_proxy', 'bindto', 'local_cert', 'local_pk'] as $k) {
  363. if ($options[$k] !== $pushedResponse->parentOptions[$k]) {
  364. return false;
  365. }
  366. }
  367. foreach (['authorization', 'cookie', 'range', 'proxy-authorization'] as $k) {
  368. $normalizedHeaders = $options['normalized_headers'][$k] ?? [];
  369. foreach ($normalizedHeaders as $i => $v) {
  370. $normalizedHeaders[$i] = substr($v, \strlen($k) + 2);
  371. }
  372. if (($pushedResponse->requestHeaders[$k] ?? []) !== $normalizedHeaders) {
  373. return false;
  374. }
  375. }
  376. return true;
  377. }
  378. /**
  379. * Wraps the request's body callback to allow it to return strings longer than curl requested.
  380. */
  381. private static function readRequestBody(int $length, \Closure $body, string &$buffer, bool &$eof): string
  382. {
  383. if (!$eof && \strlen($buffer) < $length) {
  384. if (!\is_string($data = $body($length))) {
  385. throw new TransportException(sprintf('The return value of the "body" option callback must be a string, "%s" returned.', get_debug_type($data)));
  386. }
  387. $buffer .= $data;
  388. $eof = '' === $data;
  389. }
  390. $data = substr($buffer, 0, $length);
  391. $buffer = substr($buffer, $length);
  392. return $data;
  393. }
  394. /**
  395. * Resolves relative URLs on redirects and deals with authentication headers.
  396. *
  397. * Work around CVE-2018-1000007: Authorization and Cookie headers should not follow redirects - fixed in Curl 7.64
  398. */
  399. private static function createRedirectResolver(array $options, string $host): \Closure
  400. {
  401. $redirectHeaders = [];
  402. if (0 < $options['max_redirects']) {
  403. $redirectHeaders['host'] = $host;
  404. $redirectHeaders['with_auth'] = $redirectHeaders['no_auth'] = array_filter($options['headers'], static function ($h) {
  405. return 0 !== stripos($h, 'Host:');
  406. });
  407. if (isset($options['normalized_headers']['authorization'][0]) || isset($options['normalized_headers']['cookie'][0])) {
  408. $redirectHeaders['no_auth'] = array_filter($options['headers'], static function ($h) {
  409. return 0 !== stripos($h, 'Authorization:') && 0 !== stripos($h, 'Cookie:');
  410. });
  411. }
  412. }
  413. return static function ($ch, string $location) use ($redirectHeaders) {
  414. try {
  415. $location = self::parseUrl($location);
  416. } catch (InvalidArgumentException $e) {
  417. return null;
  418. }
  419. if ($redirectHeaders && $host = parse_url('http:'.$location['authority'], \PHP_URL_HOST)) {
  420. $requestHeaders = $redirectHeaders['host'] === $host ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth'];
  421. curl_setopt($ch, \CURLOPT_HTTPHEADER, $requestHeaders);
  422. }
  423. $url = self::parseUrl(curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL));
  424. return implode('', self::resolveUrl($location, $url));
  425. };
  426. }
  427. private function findConstantName($opt): ?string
  428. {
  429. $constants = array_filter(get_defined_constants(), static function ($v, $k) use ($opt) {
  430. return $v === $opt && 'C' === $k[0] && (0 === strpos($k, 'CURLOPT_') || 0 === strpos($k, 'CURLINFO_'));
  431. }, \ARRAY_FILTER_USE_BOTH);
  432. return key($constants);
  433. }
  434. /**
  435. * Prevents overriding options that are set internally throughout the request.
  436. */
  437. private function validateExtraCurlOptions(array $options): void
  438. {
  439. $curloptsToConfig = [
  440. //options used in CurlHttpClient
  441. \CURLOPT_HTTPAUTH => 'auth_ntlm',
  442. \CURLOPT_USERPWD => 'auth_ntlm',
  443. \CURLOPT_RESOLVE => 'resolve',
  444. \CURLOPT_NOSIGNAL => 'timeout',
  445. \CURLOPT_HTTPHEADER => 'headers',
  446. \CURLOPT_INFILE => 'body',
  447. \CURLOPT_READFUNCTION => 'body',
  448. \CURLOPT_INFILESIZE => 'body',
  449. \CURLOPT_POSTFIELDS => 'body',
  450. \CURLOPT_UPLOAD => 'body',
  451. \CURLOPT_PINNEDPUBLICKEY => 'peer_fingerprint',
  452. \CURLOPT_UNIX_SOCKET_PATH => 'bindto',
  453. \CURLOPT_INTERFACE => 'bindto',
  454. \CURLOPT_TIMEOUT_MS => 'max_duration',
  455. \CURLOPT_TIMEOUT => 'max_duration',
  456. \CURLOPT_MAXREDIRS => 'max_redirects',
  457. \CURLOPT_PROXY => 'proxy',
  458. \CURLOPT_NOPROXY => 'no_proxy',
  459. \CURLOPT_SSL_VERIFYPEER => 'verify_peer',
  460. \CURLOPT_SSL_VERIFYHOST => 'verify_host',
  461. \CURLOPT_CAINFO => 'cafile',
  462. \CURLOPT_CAPATH => 'capath',
  463. \CURLOPT_SSL_CIPHER_LIST => 'ciphers',
  464. \CURLOPT_SSLCERT => 'local_cert',
  465. \CURLOPT_SSLKEY => 'local_pk',
  466. \CURLOPT_KEYPASSWD => 'passphrase',
  467. \CURLOPT_CERTINFO => 'capture_peer_cert_chain',
  468. \CURLOPT_USERAGENT => 'normalized_headers',
  469. \CURLOPT_REFERER => 'headers',
  470. //options used in CurlResponse
  471. \CURLOPT_NOPROGRESS => 'on_progress',
  472. \CURLOPT_PROGRESSFUNCTION => 'on_progress',
  473. ];
  474. $curloptsToCheck = [
  475. \CURLOPT_PRIVATE,
  476. \CURLOPT_HEADERFUNCTION,
  477. \CURLOPT_WRITEFUNCTION,
  478. \CURLOPT_VERBOSE,
  479. \CURLOPT_STDERR,
  480. \CURLOPT_RETURNTRANSFER,
  481. \CURLOPT_URL,
  482. \CURLOPT_FOLLOWLOCATION,
  483. \CURLOPT_HEADER,
  484. \CURLOPT_CONNECTTIMEOUT,
  485. \CURLOPT_CONNECTTIMEOUT_MS,
  486. \CURLOPT_HEADEROPT,
  487. \CURLOPT_HTTP_VERSION,
  488. \CURLOPT_PORT,
  489. \CURLOPT_DNS_USE_GLOBAL_CACHE,
  490. \CURLOPT_PROTOCOLS,
  491. \CURLOPT_REDIR_PROTOCOLS,
  492. \CURLOPT_COOKIEFILE,
  493. \CURLINFO_REDIRECT_COUNT,
  494. ];
  495. if (\defined('CURLOPT_HTTP09_ALLOWED')) {
  496. $curloptsToCheck[] = \CURLOPT_HTTP09_ALLOWED;
  497. }
  498. $methodOpts = [
  499. \CURLOPT_POST,
  500. \CURLOPT_PUT,
  501. \CURLOPT_CUSTOMREQUEST,
  502. \CURLOPT_HTTPGET,
  503. \CURLOPT_NOBODY,
  504. ];
  505. foreach ($options as $opt => $optValue) {
  506. if (isset($curloptsToConfig[$opt])) {
  507. $constName = $this->findConstantName($opt) ?? $opt;
  508. throw new InvalidArgumentException(sprintf('Cannot set "%s" with "extra.curl", use option "%s" instead.', $constName, $curloptsToConfig[$opt]));
  509. }
  510. if (\in_array($opt, $methodOpts)) {
  511. throw new InvalidArgumentException('The HTTP method cannot be overridden using "extra.curl".');
  512. }
  513. if (\in_array($opt, $curloptsToCheck)) {
  514. $constName = $this->findConstantName($opt) ?? $opt;
  515. throw new InvalidArgumentException(sprintf('Cannot set "%s" with "extra.curl".', $constName));
  516. }
  517. }
  518. }
  519. }