NativeHttpClient.php 17 KB

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