1
0

CheckServerResponseTrait.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCP\SetupCheck;
  8. use Generator;
  9. use OCP\Http\Client\IClientService;
  10. use OCP\Http\Client\IResponse;
  11. use OCP\IConfig;
  12. use OCP\IURLGenerator;
  13. use OCP\L10N\IFactory;
  14. use Psr\Log\LoggerInterface;
  15. /**
  16. * Common trait for setup checks that need to use requests to the same server and check the response
  17. * @since 31.0.0
  18. */
  19. trait CheckServerResponseTrait {
  20. protected IConfig $config;
  21. protected IURLGenerator $urlGenerator;
  22. protected IClientService $clientService;
  23. protected LoggerInterface $logger;
  24. /**
  25. * Common helper string in case a check could not fetch any results
  26. * @since 31.0.0
  27. */
  28. protected function serverConfigHelp(): string {
  29. $l10n = \OCP\Server::get(IFactory::class)->get('lib');
  30. return $l10n->t('To allow this check to run you have to make sure that your Web server can connect to itself. Therefore it must be able to resolve and connect to at least one of its `trusted_domains` or the `overwrite.cli.url`. This failure may be the result of a server-side DNS mismatch or outbound firewall rule.');
  31. }
  32. /**
  33. * Get all possible URLs that need to be checked for a local request test.
  34. * This takes all `trusted_domains` and the CLI overwrite URL into account.
  35. *
  36. * @param string $url The absolute path (absolute URL without host but with web-root) to test starting with a /
  37. * @param bool $isRootRequest Set to remove the web-root from URL and host (e.g. when requesting a path in the domain root like '/.well-known')
  38. * @return list<string> List of possible absolute URLs
  39. * @since 31.0.0
  40. */
  41. protected function getTestUrls(string $url, bool $isRootRequest = false): array {
  42. $url = '/' . ltrim($url, '/');
  43. $webroot = rtrim($this->urlGenerator->getWebroot(), '/');
  44. if ($isRootRequest === false && $webroot !== '' && str_starts_with($url, $webroot)) {
  45. // The URL contains the web-root but also the base url does so,
  46. // so we need to remove the web-root from the URL.
  47. $url = substr($url, strlen($webroot));
  48. }
  49. // Base URLs to test
  50. $baseUrls = [];
  51. // Try overwrite.cli.url first, it’s supposed to be how the server contacts itself
  52. $cliUrl = $this->config->getSystemValueString('overwrite.cli.url', '');
  53. if ($cliUrl !== '') {
  54. // The CLI URL already contains the web-root, so we need to normalize it if requested
  55. $baseUrls[] = $this->normalizeUrl(
  56. $cliUrl,
  57. $isRootRequest
  58. );
  59. }
  60. // Try URL generator second
  61. // The base URL also contains the webroot so also normalize it
  62. $baseUrls[] = $this->normalizeUrl(
  63. $this->urlGenerator->getBaseUrl(),
  64. $isRootRequest
  65. );
  66. /* Last resort: trusted domains */
  67. $trustedDomains = $this->config->getSystemValue('trusted_domains', []);
  68. foreach ($trustedDomains as $host) {
  69. if (str_contains($host, '*')) {
  70. /* Ignore domains with a wildcard */
  71. continue;
  72. }
  73. $baseUrls[] = $this->normalizeUrl("https://$host$webroot", $isRootRequest);
  74. $baseUrls[] = $this->normalizeUrl("http://$host$webroot", $isRootRequest);
  75. }
  76. return array_map(fn (string $host) => $host . $url, array_values(array_unique($baseUrls)));
  77. }
  78. /**
  79. * Run a HTTP request to check header
  80. * @param string $method The HTTP method to use
  81. * @param string $url The absolute path (URL with webroot but without host) to check, can be the output of `IURLGenerator`
  82. * @param bool $isRootRequest If set the webroot is removed from URLs to make the request target the host's root. Example usage are the /.well-known URLs in the root path.
  83. * @param array{ignoreSSL?: bool, httpErrors?: bool, options?: array} $options HTTP client related options, like
  84. * [
  85. * // Ignore invalid SSL certificates (e.g. self signed)
  86. * 'ignoreSSL' => true,
  87. * // Ignore requests with HTTP errors (will not yield if request has a 4xx or 5xx response)
  88. * 'httpErrors' => true,
  89. * // Additional options for the HTTP client (see `IClient`)
  90. * 'options' => [],
  91. * ]
  92. *
  93. * @return Generator<int, IResponse>
  94. * @since 31.0.0
  95. */
  96. protected function runRequest(string $method, string $url, array $options = [], bool $isRootRequest = false): Generator {
  97. $options = array_merge(['ignoreSSL' => true, 'httpErrors' => true], $options);
  98. $client = $this->clientService->newClient();
  99. $requestOptions = $this->getRequestOptions($options['ignoreSSL'], $options['httpErrors']);
  100. $requestOptions = array_merge($requestOptions, $options['options'] ?? []);
  101. foreach ($this->getTestUrls($url, $isRootRequest) as $testURL) {
  102. try {
  103. yield $client->request($method, $testURL, $requestOptions);
  104. } catch (\Throwable $e) {
  105. $this->logger->debug('Can not connect to local server for running setup checks', ['exception' => $e, 'url' => $testURL]);
  106. }
  107. }
  108. }
  109. /**
  110. * Get HTTP client options
  111. * @param bool $ignoreSSL If set SSL errors are ignored (e.g. self-signed certificates)
  112. * @since 31.0.0
  113. */
  114. private function getRequestOptions(bool $ignoreSSL, bool $httpErrors): array {
  115. $requestOptions = [
  116. 'connect_timeout' => 10,
  117. 'http_errors' => $httpErrors,
  118. 'nextcloud' => [
  119. 'allow_local_address' => true,
  120. ],
  121. ];
  122. if ($ignoreSSL) {
  123. $requestOptions['verify'] = false;
  124. }
  125. return $requestOptions;
  126. }
  127. /**
  128. * Strip a trailing slash and remove the webroot if requested.
  129. * @param string $url The URL to normalize. Should be an absolute URL containing scheme, host and optionally web-root.
  130. * @param bool $removeWebroot If set the web-root is removed from the URL and an absolute URL with only the scheme and host (optional port) is returned
  131. * @since 31.0.0
  132. */
  133. private function normalizeUrl(string $url, bool $removeWebroot): string {
  134. if ($removeWebroot) {
  135. $segments = parse_url($url);
  136. if (!isset($segments['scheme']) || !isset($segments['host'])) {
  137. throw new \InvalidArgumentException('URL is missing scheme or host');
  138. }
  139. $port = isset($segments['port']) ? (':' . $segments['port']) : '';
  140. return $segments['scheme'] . '://' . $segments['host'] . $port;
  141. }
  142. return rtrim($url, '/');
  143. }
  144. }