NativeHttpClient.php 18 KB

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