NativeHttpClient.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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\NativeClientState;
  16. use Symfony\Component\HttpClient\Response\NativeResponse;
  17. use Symfony\Component\HttpClient\Response\ResponseStream;
  18. use Symfony\Contracts\HttpClient\HttpClientInterface;
  19. use Symfony\Contracts\HttpClient\ResponseInterface;
  20. use Symfony\Contracts\HttpClient\ResponseStreamInterface;
  21. use Symfony\Contracts\Service\ResetInterface;
  22. /**
  23. * A portable implementation of the HttpClientInterface contracts based on PHP stream wrappers.
  24. *
  25. * PHP stream wrappers are able to fetch response bodies concurrently,
  26. * but each request is opened synchronously.
  27. *
  28. * @author Nicolas Grekas <p@tchwork.com>
  29. */
  30. final class NativeHttpClient implements HttpClientInterface, LoggerAwareInterface, ResetInterface
  31. {
  32. use HttpClientTrait;
  33. use LoggerAwareTrait;
  34. private array $defaultOptions = self::OPTIONS_DEFAULTS;
  35. private static array $emptyDefaults = self::OPTIONS_DEFAULTS;
  36. private $multi;
  37. /**
  38. * @param array $defaultOptions Default request's options
  39. * @param int $maxHostConnections The maximum number of connections to open
  40. *
  41. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  42. */
  43. public function __construct(array $defaultOptions = [], int $maxHostConnections = 6)
  44. {
  45. $this->defaultOptions['buffer'] = $this->defaultOptions['buffer'] ?? \Closure::fromCallable([__CLASS__, 'shouldBuffer']);
  46. if ($defaultOptions) {
  47. [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
  48. }
  49. $this->multi = new NativeClientState();
  50. $this->multi->maxHostConnections = 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX;
  51. }
  52. /**
  53. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  54. *
  55. * {@inheritdoc}
  56. */
  57. public function request(string $method, string $url, array $options = []): ResponseInterface
  58. {
  59. [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
  60. if ($options['bindto']) {
  61. if (file_exists($options['bindto'])) {
  62. throw new TransportException(__CLASS__.' cannot bind to local Unix sockets, use e.g. CurlHttpClient instead.');
  63. }
  64. if (str_starts_with($options['bindto'], 'if!')) {
  65. throw new TransportException(__CLASS__.' cannot bind to network interfaces, use e.g. CurlHttpClient instead.');
  66. }
  67. if (str_starts_with($options['bindto'], 'host!')) {
  68. $options['bindto'] = substr($options['bindto'], 5);
  69. }
  70. }
  71. $hasContentLength = isset($options['normalized_headers']['content-length']);
  72. $hasBody = '' !== $options['body'] || 'POST' === $method || $hasContentLength;
  73. $options['body'] = self::getBodyAsString($options['body']);
  74. if ('chunked' === substr($options['normalized_headers']['transfer-encoding'][0] ?? '', \strlen('Transfer-Encoding: '))) {
  75. unset($options['normalized_headers']['transfer-encoding']);
  76. $options['headers'] = array_merge(...array_values($options['normalized_headers']));
  77. $options['body'] = self::dechunk($options['body']);
  78. }
  79. if ('' === $options['body'] && $hasBody && !$hasContentLength) {
  80. $options['headers'][] = 'Content-Length: 0';
  81. }
  82. if ($hasBody && !isset($options['normalized_headers']['content-type'])) {
  83. $options['headers'][] = 'Content-Type: application/x-www-form-urlencoded';
  84. }
  85. if (\extension_loaded('zlib') && !isset($options['normalized_headers']['accept-encoding'])) {
  86. // gzip is the most widely available algo, no need to deal with deflate
  87. $options['headers'][] = 'Accept-Encoding: gzip';
  88. }
  89. if ($options['peer_fingerprint']) {
  90. if (isset($options['peer_fingerprint']['pin-sha256']) && 1 === \count($options['peer_fingerprint'])) {
  91. throw new TransportException(__CLASS__.' cannot verify "pin-sha256" fingerprints, please provide a "sha256" one.');
  92. }
  93. unset($options['peer_fingerprint']['pin-sha256']);
  94. }
  95. $info = [
  96. 'response_headers' => [],
  97. 'url' => $url,
  98. 'error' => null,
  99. 'canceled' => false,
  100. 'http_method' => $method,
  101. 'http_code' => 0,
  102. 'redirect_count' => 0,
  103. 'start_time' => 0.0,
  104. 'connect_time' => 0.0,
  105. 'redirect_time' => 0.0,
  106. 'pretransfer_time' => 0.0,
  107. 'starttransfer_time' => 0.0,
  108. 'total_time' => 0.0,
  109. 'namelookup_time' => 0.0,
  110. 'size_upload' => 0,
  111. 'size_download' => 0,
  112. 'size_body' => \strlen($options['body']),
  113. 'primary_ip' => '',
  114. 'primary_port' => 'http:' === $url['scheme'] ? 80 : 443,
  115. 'debug' => \extension_loaded('curl') ? '' : "* Enable the curl extension for better performance\n",
  116. ];
  117. if ($onProgress = $options['on_progress']) {
  118. // Memoize the last progress to ease calling the callback periodically when no network transfer happens
  119. $lastProgress = [0, 0];
  120. $maxDuration = 0 < $options['max_duration'] ? $options['max_duration'] : \INF;
  121. $onProgress = static function (...$progress) use ($onProgress, &$lastProgress, &$info, $maxDuration) {
  122. if ($info['total_time'] >= $maxDuration) {
  123. throw new TransportException(sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
  124. }
  125. $progressInfo = $info;
  126. $progressInfo['url'] = implode('', $info['url']);
  127. unset($progressInfo['size_body']);
  128. if ($progress && -1 === $progress[0]) {
  129. // Response completed
  130. $lastProgress[0] = max($lastProgress);
  131. } else {
  132. $lastProgress = $progress ?: $lastProgress;
  133. }
  134. $onProgress($lastProgress[0], $lastProgress[1], $progressInfo);
  135. };
  136. } elseif (0 < $options['max_duration']) {
  137. $maxDuration = $options['max_duration'];
  138. $onProgress = static function () use (&$info, $maxDuration): void {
  139. if ($info['total_time'] >= $maxDuration) {
  140. throw new TransportException(sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
  141. }
  142. };
  143. }
  144. // Always register a notification callback to compute live stats about the response
  145. $notification = static function (int $code, int $severity, ?string $msg, int $msgCode, int $dlNow, int $dlSize) use ($onProgress, &$info) {
  146. $info['total_time'] = microtime(true) - $info['start_time'];
  147. if (\STREAM_NOTIFY_PROGRESS === $code) {
  148. $info['starttransfer_time'] = $info['starttransfer_time'] ?: $info['total_time'];
  149. $info['size_upload'] += $dlNow ? 0 : $info['size_body'];
  150. $info['size_download'] = $dlNow;
  151. } elseif (\STREAM_NOTIFY_CONNECT === $code) {
  152. $info['connect_time'] = $info['total_time'];
  153. $info['debug'] .= $info['request_header'];
  154. unset($info['request_header']);
  155. } else {
  156. return;
  157. }
  158. if ($onProgress) {
  159. $onProgress($dlNow, $dlSize);
  160. }
  161. };
  162. if ($options['resolve']) {
  163. $this->multi->dnsCache = $options['resolve'] + $this->multi->dnsCache;
  164. }
  165. $this->logger && $this->logger->info(sprintf('Request: "%s %s"', $method, implode('', $url)));
  166. if (!isset($options['normalized_headers']['user-agent'])) {
  167. $options['headers'][] = 'User-Agent: Symfony HttpClient/Native';
  168. }
  169. if (0 < $options['max_duration']) {
  170. $options['timeout'] = min($options['max_duration'], $options['timeout']);
  171. }
  172. $context = [
  173. 'http' => [
  174. 'protocol_version' => min($options['http_version'] ?: '1.1', '1.1'),
  175. 'method' => $method,
  176. 'content' => $options['body'],
  177. 'ignore_errors' => true,
  178. 'curl_verify_ssl_peer' => $options['verify_peer'],
  179. 'curl_verify_ssl_host' => $options['verify_host'],
  180. 'auto_decode' => false, // Disable dechunk filter, it's incompatible with stream_select()
  181. 'timeout' => $options['timeout'],
  182. 'follow_location' => false, // We follow redirects ourselves - the native logic is too limited
  183. ],
  184. 'ssl' => array_filter([
  185. 'verify_peer' => $options['verify_peer'],
  186. 'verify_peer_name' => $options['verify_host'],
  187. 'cafile' => $options['cafile'],
  188. 'capath' => $options['capath'],
  189. 'local_cert' => $options['local_cert'],
  190. 'local_pk' => $options['local_pk'],
  191. 'passphrase' => $options['passphrase'],
  192. 'ciphers' => $options['ciphers'],
  193. 'peer_fingerprint' => $options['peer_fingerprint'],
  194. 'capture_peer_cert_chain' => $options['capture_peer_cert_chain'],
  195. 'allow_self_signed' => (bool) $options['peer_fingerprint'],
  196. 'SNI_enabled' => true,
  197. 'disable_compression' => true,
  198. ], static function ($v) { return null !== $v; }),
  199. 'socket' => [
  200. 'bindto' => $options['bindto'],
  201. 'tcp_nodelay' => true,
  202. ],
  203. ];
  204. $context = stream_context_create($context, ['notification' => $notification]);
  205. $resolver = static function ($multi) use ($context, $options, $url, &$info, $onProgress) {
  206. [$host, $port] = self::parseHostPort($url, $info);
  207. if (!isset($options['normalized_headers']['host'])) {
  208. $options['headers'][] = 'Host: '.$host.$port;
  209. }
  210. $proxy = self::getProxy($options['proxy'], $url, $options['no_proxy']);
  211. if (!self::configureHeadersAndProxy($context, $host, $options['headers'], $proxy, 'https:' === $url['scheme'])) {
  212. $ip = self::dnsResolve($host, $multi, $info, $onProgress);
  213. $url['authority'] = substr_replace($url['authority'], $ip, -\strlen($host) - \strlen($port), \strlen($host));
  214. }
  215. return [self::createRedirectResolver($options, $host, $proxy, $info, $onProgress), implode('', $url)];
  216. };
  217. return new NativeResponse($this->multi, $context, implode('', $url), $options, $info, $resolver, $onProgress, $this->logger);
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. public function stream(ResponseInterface|iterable $responses, float $timeout = null): ResponseStreamInterface
  223. {
  224. if ($responses instanceof NativeResponse) {
  225. $responses = [$responses];
  226. }
  227. return new ResponseStream(NativeResponse::stream($responses, $timeout));
  228. }
  229. public function reset()
  230. {
  231. $this->multi->reset();
  232. }
  233. private static function getBodyAsString($body): string
  234. {
  235. if (\is_resource($body)) {
  236. return stream_get_contents($body);
  237. }
  238. if (!$body instanceof \Closure) {
  239. return $body;
  240. }
  241. $result = '';
  242. while ('' !== $data = $body(self::$CHUNK_SIZE)) {
  243. if (!\is_string($data)) {
  244. throw new TransportException(sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
  245. }
  246. $result .= $data;
  247. }
  248. return $result;
  249. }
  250. /**
  251. * Extracts the host and the port from the URL.
  252. */
  253. private static function parseHostPort(array $url, array &$info): array
  254. {
  255. if ($port = parse_url($url['authority'], \PHP_URL_PORT) ?: '') {
  256. $info['primary_port'] = $port;
  257. $port = ':'.$port;
  258. } else {
  259. $info['primary_port'] = 'http:' === $url['scheme'] ? 80 : 443;
  260. }
  261. return [parse_url($url['authority'], \PHP_URL_HOST), $port];
  262. }
  263. /**
  264. * Resolves the IP of the host using the local DNS cache if possible.
  265. */
  266. private static function dnsResolve(string $host, NativeClientState $multi, array &$info, ?\Closure $onProgress): string
  267. {
  268. if (null === $ip = $multi->dnsCache[$host] ?? null) {
  269. $info['debug'] .= "* Hostname was NOT found in DNS cache\n";
  270. $now = microtime(true);
  271. if (!$ip = gethostbynamel($host)) {
  272. throw new TransportException(sprintf('Could not resolve host "%s".', $host));
  273. }
  274. $info['namelookup_time'] = microtime(true) - ($info['start_time'] ?: $now);
  275. $multi->dnsCache[$host] = $ip = $ip[0];
  276. $info['debug'] .= "* Added {$host}:0:{$ip} to DNS cache\n";
  277. } else {
  278. $info['debug'] .= "* Hostname was found in DNS cache\n";
  279. }
  280. $info['primary_ip'] = $ip;
  281. if ($onProgress) {
  282. // Notify DNS resolution
  283. $onProgress();
  284. }
  285. return $ip;
  286. }
  287. /**
  288. * Handles redirects - the native logic is too buggy to be used.
  289. */
  290. private static function createRedirectResolver(array $options, string $host, ?array $proxy, array &$info, ?\Closure $onProgress): \Closure
  291. {
  292. $redirectHeaders = [];
  293. if (0 < $maxRedirects = $options['max_redirects']) {
  294. $redirectHeaders = ['host' => $host];
  295. $redirectHeaders['with_auth'] = $redirectHeaders['no_auth'] = array_filter($options['headers'], static function ($h) {
  296. return 0 !== stripos($h, 'Host:');
  297. });
  298. if (isset($options['normalized_headers']['authorization']) || isset($options['normalized_headers']['cookie'])) {
  299. $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], static function ($h) {
  300. return 0 !== stripos($h, 'Authorization:') && 0 !== stripos($h, 'Cookie:');
  301. });
  302. }
  303. }
  304. return static function (NativeClientState $multi, ?string $location, $context) use (&$redirectHeaders, $proxy, &$info, $maxRedirects, $onProgress): ?string {
  305. if (null === $location || $info['http_code'] < 300 || 400 <= $info['http_code']) {
  306. $info['redirect_url'] = null;
  307. return null;
  308. }
  309. try {
  310. $url = self::parseUrl($location);
  311. } catch (InvalidArgumentException $e) {
  312. $info['redirect_url'] = null;
  313. return null;
  314. }
  315. $url = self::resolveUrl($url, $info['url']);
  316. $info['redirect_url'] = implode('', $url);
  317. if ($info['redirect_count'] >= $maxRedirects) {
  318. return null;
  319. }
  320. $info['url'] = $url;
  321. ++$info['redirect_count'];
  322. $info['redirect_time'] = microtime(true) - $info['start_time'];
  323. // Do like curl and browsers: turn POST to GET on 301, 302 and 303
  324. if (\in_array($info['http_code'], [301, 302, 303], true)) {
  325. $options = stream_context_get_options($context)['http'];
  326. if ('POST' === $options['method'] || 303 === $info['http_code']) {
  327. $info['http_method'] = $options['method'] = 'HEAD' === $options['method'] ? 'HEAD' : 'GET';
  328. $options['content'] = '';
  329. $filterContentHeaders = static function ($h) {
  330. return 0 !== stripos($h, 'Content-Length:') && 0 !== stripos($h, 'Content-Type:') && 0 !== stripos($h, 'Transfer-Encoding:');
  331. };
  332. $options['header'] = array_filter($options['header'], $filterContentHeaders);
  333. $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], $filterContentHeaders);
  334. $redirectHeaders['with_auth'] = array_filter($redirectHeaders['with_auth'], $filterContentHeaders);
  335. stream_context_set_option($context, ['http' => $options]);
  336. }
  337. }
  338. [$host, $port] = self::parseHostPort($url, $info);
  339. if (false !== (parse_url($location, \PHP_URL_HOST) ?? false)) {
  340. // Authorization and Cookie headers MUST NOT follow except for the initial host name
  341. $requestHeaders = $redirectHeaders['host'] === $host ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth'];
  342. $requestHeaders[] = 'Host: '.$host.$port;
  343. $dnsResolve = !self::configureHeadersAndProxy($context, $host, $requestHeaders, $proxy, 'https:' === $url['scheme']);
  344. } else {
  345. $dnsResolve = isset(stream_context_get_options($context)['ssl']['peer_name']);
  346. }
  347. if ($dnsResolve) {
  348. $ip = self::dnsResolve($host, $multi, $info, $onProgress);
  349. $url['authority'] = substr_replace($url['authority'], $ip, -\strlen($host) - \strlen($port), \strlen($host));
  350. }
  351. return implode('', $url);
  352. };
  353. }
  354. private static function configureHeadersAndProxy($context, string $host, array $requestHeaders, ?array $proxy, bool $isSsl): bool
  355. {
  356. if (null === $proxy) {
  357. stream_context_set_option($context, 'http', 'header', $requestHeaders);
  358. stream_context_set_option($context, 'ssl', 'peer_name', $host);
  359. return false;
  360. }
  361. // Matching "no_proxy" should follow the behavior of curl
  362. foreach ($proxy['no_proxy'] as $rule) {
  363. $dotRule = '.'.ltrim($rule, '.');
  364. if ('*' === $rule || $host === $rule || str_ends_with($host, $dotRule)) {
  365. stream_context_set_option($context, 'http', 'proxy', null);
  366. stream_context_set_option($context, 'http', 'request_fulluri', false);
  367. stream_context_set_option($context, 'http', 'header', $requestHeaders);
  368. stream_context_set_option($context, 'ssl', 'peer_name', $host);
  369. return false;
  370. }
  371. }
  372. if (null !== $proxy['auth']) {
  373. $requestHeaders[] = 'Proxy-Authorization: '.$proxy['auth'];
  374. }
  375. stream_context_set_option($context, 'http', 'proxy', $proxy['url']);
  376. stream_context_set_option($context, 'http', 'request_fulluri', !$isSsl);
  377. stream_context_set_option($context, 'http', 'header', $requestHeaders);
  378. stream_context_set_option($context, 'ssl', 'peer_name', null);
  379. return true;
  380. }
  381. }