StreamHandler.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. namespace GuzzleHttp\Handler;
  3. use GuzzleHttp\Exception\ConnectException;
  4. use GuzzleHttp\Exception\RequestException;
  5. use GuzzleHttp\Promise as P;
  6. use GuzzleHttp\Promise\FulfilledPromise;
  7. use GuzzleHttp\Promise\PromiseInterface;
  8. use GuzzleHttp\Psr7;
  9. use GuzzleHttp\TransferStats;
  10. use GuzzleHttp\Utils;
  11. use Psr\Http\Message\RequestInterface;
  12. use Psr\Http\Message\ResponseInterface;
  13. use Psr\Http\Message\StreamInterface;
  14. use Psr\Http\Message\UriInterface;
  15. /**
  16. * HTTP handler that uses PHP's HTTP stream wrapper.
  17. *
  18. * @final
  19. */
  20. class StreamHandler
  21. {
  22. /**
  23. * @var array
  24. */
  25. private $lastHeaders = [];
  26. /**
  27. * Sends an HTTP request.
  28. *
  29. * @param RequestInterface $request Request to send.
  30. * @param array $options Request transfer options.
  31. */
  32. public function __invoke(RequestInterface $request, array $options): PromiseInterface
  33. {
  34. // Sleep if there is a delay specified.
  35. if (isset($options['delay'])) {
  36. \usleep($options['delay'] * 1000);
  37. }
  38. $startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
  39. try {
  40. // Does not support the expect header.
  41. $request = $request->withoutHeader('Expect');
  42. // Append a content-length header if body size is zero to match
  43. // cURL's behavior.
  44. if (0 === $request->getBody()->getSize()) {
  45. $request = $request->withHeader('Content-Length', '0');
  46. }
  47. return $this->createResponse(
  48. $request,
  49. $options,
  50. $this->createStream($request, $options),
  51. $startTime
  52. );
  53. } catch (\InvalidArgumentException $e) {
  54. throw $e;
  55. } catch (\Exception $e) {
  56. // Determine if the error was a networking error.
  57. $message = $e->getMessage();
  58. // This list can probably get more comprehensive.
  59. if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed
  60. || false !== \strpos($message, 'Connection refused')
  61. || false !== \strpos($message, "couldn't connect to host") // error on HHVM
  62. || false !== \strpos($message, 'connection attempt failed')
  63. ) {
  64. $e = new ConnectException($e->getMessage(), $request, $e);
  65. } else {
  66. $e = RequestException::wrapException($request, $e);
  67. }
  68. $this->invokeStats($options, $request, $startTime, null, $e);
  69. return P\Create::rejectionFor($e);
  70. }
  71. }
  72. private function invokeStats(
  73. array $options,
  74. RequestInterface $request,
  75. ?float $startTime,
  76. ResponseInterface $response = null,
  77. \Throwable $error = null
  78. ): void {
  79. if (isset($options['on_stats'])) {
  80. $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []);
  81. ($options['on_stats'])($stats);
  82. }
  83. }
  84. /**
  85. * @param resource $stream
  86. */
  87. private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface
  88. {
  89. $hdrs = $this->lastHeaders;
  90. $this->lastHeaders = [];
  91. try {
  92. [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs);
  93. } catch (\Exception $e) {
  94. return P\Create::rejectionFor(
  95. new RequestException('An error was encountered while creating the response', $request, null, $e)
  96. );
  97. }
  98. [$stream, $headers] = $this->checkDecode($options, $headers, $stream);
  99. $stream = Psr7\Utils::streamFor($stream);
  100. $sink = $stream;
  101. if (\strcasecmp('HEAD', $request->getMethod())) {
  102. $sink = $this->createSink($stream, $options);
  103. }
  104. try {
  105. $response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
  106. } catch (\Exception $e) {
  107. return P\Create::rejectionFor(
  108. new RequestException('An error was encountered while creating the response', $request, null, $e)
  109. );
  110. }
  111. if (isset($options['on_headers'])) {
  112. try {
  113. $options['on_headers']($response);
  114. } catch (\Exception $e) {
  115. return P\Create::rejectionFor(
  116. new RequestException('An error was encountered during the on_headers event', $request, $response, $e)
  117. );
  118. }
  119. }
  120. // Do not drain when the request is a HEAD request because they have
  121. // no body.
  122. if ($sink !== $stream) {
  123. $this->drain($stream, $sink, $response->getHeaderLine('Content-Length'));
  124. }
  125. $this->invokeStats($options, $request, $startTime, $response, null);
  126. return new FulfilledPromise($response);
  127. }
  128. private function createSink(StreamInterface $stream, array $options): StreamInterface
  129. {
  130. if (!empty($options['stream'])) {
  131. return $stream;
  132. }
  133. $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+');
  134. return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink);
  135. }
  136. /**
  137. * @param resource $stream
  138. */
  139. private function checkDecode(array $options, array $headers, $stream): array
  140. {
  141. // Automatically decode responses when instructed.
  142. if (!empty($options['decode_content'])) {
  143. $normalizedKeys = Utils::normalizeHeaderKeys($headers);
  144. if (isset($normalizedKeys['content-encoding'])) {
  145. $encoding = $headers[$normalizedKeys['content-encoding']];
  146. if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') {
  147. $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream));
  148. $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
  149. // Remove content-encoding header
  150. unset($headers[$normalizedKeys['content-encoding']]);
  151. // Fix content-length header
  152. if (isset($normalizedKeys['content-length'])) {
  153. $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
  154. $length = (int) $stream->getSize();
  155. if ($length === 0) {
  156. unset($headers[$normalizedKeys['content-length']]);
  157. } else {
  158. $headers[$normalizedKeys['content-length']] = [$length];
  159. }
  160. }
  161. }
  162. }
  163. }
  164. return [$stream, $headers];
  165. }
  166. /**
  167. * Drains the source stream into the "sink" client option.
  168. *
  169. * @param string $contentLength Header specifying the amount of
  170. * data to read.
  171. *
  172. * @throws \RuntimeException when the sink option is invalid.
  173. */
  174. private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface
  175. {
  176. // If a content-length header is provided, then stop reading once
  177. // that number of bytes has been read. This can prevent infinitely
  178. // reading from a stream when dealing with servers that do not honor
  179. // Connection: Close headers.
  180. Psr7\Utils::copyToStream(
  181. $source,
  182. $sink,
  183. (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1
  184. );
  185. $sink->seek(0);
  186. $source->close();
  187. return $sink;
  188. }
  189. /**
  190. * Create a resource and check to ensure it was created successfully
  191. *
  192. * @param callable $callback Callable that returns stream resource
  193. *
  194. * @return resource
  195. *
  196. * @throws \RuntimeException on error
  197. */
  198. private function createResource(callable $callback)
  199. {
  200. $errors = [];
  201. \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool {
  202. $errors[] = [
  203. 'message' => $msg,
  204. 'file' => $file,
  205. 'line' => $line,
  206. ];
  207. return true;
  208. });
  209. try {
  210. $resource = $callback();
  211. } finally {
  212. \restore_error_handler();
  213. }
  214. if (!$resource) {
  215. $message = 'Error creating resource: ';
  216. foreach ($errors as $err) {
  217. foreach ($err as $key => $value) {
  218. $message .= "[$key] $value".\PHP_EOL;
  219. }
  220. }
  221. throw new \RuntimeException(\trim($message));
  222. }
  223. return $resource;
  224. }
  225. /**
  226. * @return resource
  227. */
  228. private function createStream(RequestInterface $request, array $options)
  229. {
  230. static $methods;
  231. if (!$methods) {
  232. $methods = \array_flip(\get_class_methods(__CLASS__));
  233. }
  234. if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) {
  235. throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request);
  236. }
  237. // HTTP/1.1 streams using the PHP stream wrapper require a
  238. // Connection: close header
  239. if ($request->getProtocolVersion() == '1.1'
  240. && !$request->hasHeader('Connection')
  241. ) {
  242. $request = $request->withHeader('Connection', 'close');
  243. }
  244. // Ensure SSL is verified by default
  245. if (!isset($options['verify'])) {
  246. $options['verify'] = true;
  247. }
  248. $params = [];
  249. $context = $this->getDefaultContext($request);
  250. if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) {
  251. throw new \InvalidArgumentException('on_headers must be callable');
  252. }
  253. if (!empty($options)) {
  254. foreach ($options as $key => $value) {
  255. $method = "add_{$key}";
  256. if (isset($methods[$method])) {
  257. $this->{$method}($request, $context, $value, $params);
  258. }
  259. }
  260. }
  261. if (isset($options['stream_context'])) {
  262. if (!\is_array($options['stream_context'])) {
  263. throw new \InvalidArgumentException('stream_context must be an array');
  264. }
  265. $context = \array_replace_recursive($context, $options['stream_context']);
  266. }
  267. // Microsoft NTLM authentication only supported with curl handler
  268. if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) {
  269. throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler');
  270. }
  271. $uri = $this->resolveHost($request, $options);
  272. $contextResource = $this->createResource(
  273. static function () use ($context, $params) {
  274. return \stream_context_create($context, $params);
  275. }
  276. );
  277. return $this->createResource(
  278. function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) {
  279. $resource = @\fopen((string) $uri, 'r', false, $contextResource);
  280. $this->lastHeaders = $http_response_header ?? [];
  281. if (false === $resource) {
  282. throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context);
  283. }
  284. if (isset($options['read_timeout'])) {
  285. $readTimeout = $options['read_timeout'];
  286. $sec = (int) $readTimeout;
  287. $usec = ($readTimeout - $sec) * 100000;
  288. \stream_set_timeout($resource, $sec, $usec);
  289. }
  290. return $resource;
  291. }
  292. );
  293. }
  294. private function resolveHost(RequestInterface $request, array $options): UriInterface
  295. {
  296. $uri = $request->getUri();
  297. if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) {
  298. if ('v4' === $options['force_ip_resolve']) {
  299. $records = \dns_get_record($uri->getHost(), \DNS_A);
  300. if (false === $records || !isset($records[0]['ip'])) {
  301. throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
  302. }
  303. return $uri->withHost($records[0]['ip']);
  304. }
  305. if ('v6' === $options['force_ip_resolve']) {
  306. $records = \dns_get_record($uri->getHost(), \DNS_AAAA);
  307. if (false === $records || !isset($records[0]['ipv6'])) {
  308. throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
  309. }
  310. return $uri->withHost('['.$records[0]['ipv6'].']');
  311. }
  312. }
  313. return $uri;
  314. }
  315. private function getDefaultContext(RequestInterface $request): array
  316. {
  317. $headers = '';
  318. foreach ($request->getHeaders() as $name => $value) {
  319. foreach ($value as $val) {
  320. $headers .= "$name: $val\r\n";
  321. }
  322. }
  323. $context = [
  324. 'http' => [
  325. 'method' => $request->getMethod(),
  326. 'header' => $headers,
  327. 'protocol_version' => $request->getProtocolVersion(),
  328. 'ignore_errors' => true,
  329. 'follow_location' => 0,
  330. ],
  331. 'ssl' => [
  332. 'peer_name' => $request->getUri()->getHost(),
  333. ],
  334. ];
  335. $body = (string) $request->getBody();
  336. if ('' !== $body) {
  337. $context['http']['content'] = $body;
  338. // Prevent the HTTP handler from adding a Content-Type header.
  339. if (!$request->hasHeader('Content-Type')) {
  340. $context['http']['header'] .= "Content-Type:\r\n";
  341. }
  342. }
  343. $context['http']['header'] = \rtrim($context['http']['header']);
  344. return $context;
  345. }
  346. /**
  347. * @param mixed $value as passed via Request transfer options.
  348. */
  349. private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void
  350. {
  351. $uri = null;
  352. if (!\is_array($value)) {
  353. $uri = $value;
  354. } else {
  355. $scheme = $request->getUri()->getScheme();
  356. if (isset($value[$scheme])) {
  357. if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) {
  358. $uri = $value[$scheme];
  359. }
  360. }
  361. }
  362. if (!$uri) {
  363. return;
  364. }
  365. $parsed = $this->parse_proxy($uri);
  366. $options['http']['proxy'] = $parsed['proxy'];
  367. if ($parsed['auth']) {
  368. if (!isset($options['http']['header'])) {
  369. $options['http']['header'] = [];
  370. }
  371. $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}";
  372. }
  373. }
  374. /**
  375. * Parses the given proxy URL to make it compatible with the format PHP's stream context expects.
  376. */
  377. private function parse_proxy(string $url): array
  378. {
  379. $parsed = \parse_url($url);
  380. if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
  381. if (isset($parsed['host']) && isset($parsed['port'])) {
  382. $auth = null;
  383. if (isset($parsed['user']) && isset($parsed['pass'])) {
  384. $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}");
  385. }
  386. return [
  387. 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}",
  388. 'auth' => $auth ? "Basic {$auth}" : null,
  389. ];
  390. }
  391. }
  392. // Return proxy as-is.
  393. return [
  394. 'proxy' => $url,
  395. 'auth' => null,
  396. ];
  397. }
  398. /**
  399. * @param mixed $value as passed via Request transfer options.
  400. */
  401. private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void
  402. {
  403. if ($value > 0) {
  404. $options['http']['timeout'] = $value;
  405. }
  406. }
  407. /**
  408. * @param mixed $value as passed via Request transfer options.
  409. */
  410. private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void
  411. {
  412. if (
  413. $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  414. || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  415. || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  416. || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT)
  417. ) {
  418. $options['http']['crypto_method'] = $value;
  419. return;
  420. }
  421. throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
  422. }
  423. /**
  424. * @param mixed $value as passed via Request transfer options.
  425. */
  426. private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void
  427. {
  428. if ($value === false) {
  429. $options['ssl']['verify_peer'] = false;
  430. $options['ssl']['verify_peer_name'] = false;
  431. return;
  432. }
  433. if (\is_string($value)) {
  434. $options['ssl']['cafile'] = $value;
  435. if (!\file_exists($value)) {
  436. throw new \RuntimeException("SSL CA bundle not found: $value");
  437. }
  438. } elseif ($value !== true) {
  439. throw new \InvalidArgumentException('Invalid verify request option');
  440. }
  441. $options['ssl']['verify_peer'] = true;
  442. $options['ssl']['verify_peer_name'] = true;
  443. $options['ssl']['allow_self_signed'] = false;
  444. }
  445. /**
  446. * @param mixed $value as passed via Request transfer options.
  447. */
  448. private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void
  449. {
  450. if (\is_array($value)) {
  451. $options['ssl']['passphrase'] = $value[1];
  452. $value = $value[0];
  453. }
  454. if (!\file_exists($value)) {
  455. throw new \RuntimeException("SSL certificate not found: {$value}");
  456. }
  457. $options['ssl']['local_cert'] = $value;
  458. }
  459. /**
  460. * @param mixed $value as passed via Request transfer options.
  461. */
  462. private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void
  463. {
  464. self::addNotification(
  465. $params,
  466. static function ($code, $a, $b, $c, $transferred, $total) use ($value) {
  467. if ($code == \STREAM_NOTIFY_PROGRESS) {
  468. // The upload progress cannot be determined. Use 0 for cURL compatibility:
  469. // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html
  470. $value($total, $transferred, 0, 0);
  471. }
  472. }
  473. );
  474. }
  475. /**
  476. * @param mixed $value as passed via Request transfer options.
  477. */
  478. private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void
  479. {
  480. if ($value === false) {
  481. return;
  482. }
  483. static $map = [
  484. \STREAM_NOTIFY_CONNECT => 'CONNECT',
  485. \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
  486. \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
  487. \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
  488. \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
  489. \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
  490. \STREAM_NOTIFY_PROGRESS => 'PROGRESS',
  491. \STREAM_NOTIFY_FAILURE => 'FAILURE',
  492. \STREAM_NOTIFY_COMPLETED => 'COMPLETED',
  493. \STREAM_NOTIFY_RESOLVE => 'RESOLVE',
  494. ];
  495. static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max'];
  496. $value = Utils::debugResource($value);
  497. $ident = $request->getMethod().' '.$request->getUri()->withFragment('');
  498. self::addNotification(
  499. $params,
  500. static function (int $code, ...$passed) use ($ident, $value, $map, $args): void {
  501. \fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
  502. foreach (\array_filter($passed) as $i => $v) {
  503. \fwrite($value, $args[$i].': "'.$v.'" ');
  504. }
  505. \fwrite($value, "\n");
  506. }
  507. );
  508. }
  509. private static function addNotification(array &$params, callable $notify): void
  510. {
  511. // Wrap the existing function if needed.
  512. if (!isset($params['notification'])) {
  513. $params['notification'] = $notify;
  514. } else {
  515. $params['notification'] = self::callArray([
  516. $params['notification'],
  517. $notify,
  518. ]);
  519. }
  520. }
  521. private static function callArray(array $functions): callable
  522. {
  523. return static function (...$args) use ($functions) {
  524. foreach ($functions as $fn) {
  525. $fn(...$args);
  526. }
  527. };
  528. }
  529. }