CurlHttpClient.php 23 KB

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