CurlHttpClient.php 23 KB

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