CheckServerResponseTrait.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 OCA\Settings\SetupChecks;
  8. use Generator;
  9. use OCP\Http\Client\IClientService;
  10. use OCP\Http\Client\IResponse;
  11. use OCP\IConfig;
  12. use OCP\IL10N;
  13. use OCP\IURLGenerator;
  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. */
  18. trait CheckServerResponseTrait {
  19. protected IConfig $config;
  20. protected IURLGenerator $urlGenerator;
  21. protected IClientService $clientService;
  22. protected IL10N $l10n;
  23. protected LoggerInterface $logger;
  24. /**
  25. * Common helper string in case a check could not fetch any results
  26. */
  27. protected function serverConfigHelp(): string {
  28. return $this->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.');
  29. }
  30. /**
  31. * Get all possible URLs that need to be checked for a local request test.
  32. * This takes all `trusted_domains` and the CLI overwrite URL into account.
  33. *
  34. * @param string $url The absolute path (absolute URL without host but with web-root) to test starting with a /
  35. * @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')
  36. * @return list<string> List of possible absolute URLs
  37. */
  38. protected function getTestUrls(string $url, bool $isRootRequest = false): array {
  39. $url = '/' . ltrim($url, '/');
  40. $webroot = rtrim($this->urlGenerator->getWebroot(), '/');
  41. if ($isRootRequest === false && $webroot !== '' && str_starts_with($url, $webroot)) {
  42. // The URL contains the web-root but also the base url does so,
  43. // so we need to remove the web-root from the URL.
  44. $url = substr($url, strlen($webroot));
  45. }
  46. // Base URLs to test
  47. $baseUrls = [];
  48. // Try overwrite.cli.url first, it’s supposed to be how the server contacts itself
  49. $cliUrl = $this->config->getSystemValueString('overwrite.cli.url', '');
  50. if ($cliUrl !== '') {
  51. // The CLI URL already contains the web-root, so we need to normalize it if requested
  52. $baseUrls[] = $this->normalizeUrl(
  53. $cliUrl,
  54. $isRootRequest
  55. );
  56. }
  57. // Try URL generator second
  58. // The base URL also contains the webroot so also normalize it
  59. $baseUrls[] = $this->normalizeUrl(
  60. $this->urlGenerator->getBaseUrl(),
  61. $isRootRequest
  62. );
  63. /* Last resort: trusted domains */
  64. $trustedDomains = $this->config->getSystemValue('trusted_domains', []);
  65. foreach ($trustedDomains as $host) {
  66. if (str_contains($host, '*')) {
  67. /* Ignore domains with a wildcard */
  68. continue;
  69. }
  70. $baseUrls[] = $this->normalizeUrl("https://$host$webroot", $isRootRequest);
  71. $baseUrls[] = $this->normalizeUrl("http://$host$webroot", $isRootRequest);
  72. }
  73. return array_map(fn (string $host) => $host . $url, array_values(array_unique($baseUrls)));
  74. }
  75. /**
  76. * Strip a trailing slash and remove the webroot if requested.
  77. * @param string $url The URL to normalize. Should be an absolute URL containing scheme, host and optionally web-root.
  78. * @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
  79. */
  80. protected function normalizeUrl(string $url, bool $removeWebroot): string {
  81. if ($removeWebroot) {
  82. $segments = parse_url($url);
  83. $port = isset($segments['port']) ? (':' . $segments['port']) : '';
  84. return $segments['scheme'] . '://' . $segments['host'] . $port;
  85. }
  86. return rtrim($url, '/');
  87. }
  88. /**
  89. * Run a HTTP request to check header
  90. * @param string $method The HTTP method to use
  91. * @param string $url The absolute path (URL with webroot but without host) to check, can be the output of `IURLGenerator`
  92. * @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.
  93. * @param array{ignoreSSL?: bool, httpErrors?: bool, options?: array} $options HTTP client related options, like
  94. * [
  95. * // Ignore invalid SSL certificates (e.g. self signed)
  96. * 'ignoreSSL' => true,
  97. * // Ignore requests with HTTP errors (will not yield if request has a 4xx or 5xx response)
  98. * 'httpErrors' => true,
  99. * // Additional options for the HTTP client (see `IClient`)
  100. * 'options' => [],
  101. * ]
  102. *
  103. * @return Generator<int, IResponse>
  104. */
  105. protected function runRequest(string $method, string $url, array $options = [], bool $isRootRequest = false): Generator {
  106. $options = array_merge(['ignoreSSL' => true, 'httpErrors' => true], $options);
  107. $client = $this->clientService->newClient();
  108. $requestOptions = $this->getRequestOptions($options['ignoreSSL'], $options['httpErrors']);
  109. $requestOptions = array_merge($requestOptions, $options['options'] ?? []);
  110. foreach ($this->getTestUrls($url, $isRootRequest) as $testURL) {
  111. try {
  112. yield $client->request($method, $testURL, $requestOptions);
  113. } catch (\Throwable $e) {
  114. $this->logger->debug('Can not connect to local server for running setup checks', ['exception' => $e, 'url' => $testURL]);
  115. }
  116. }
  117. }
  118. /**
  119. * Run a HEAD request to check header
  120. * @param string $url The relative URL to check (e.g. output of IURLGenerator)
  121. * @param bool $ignoreSSL Ignore SSL certificates
  122. * @param bool $httpErrors Ignore requests with HTTP errors (will not yield if request has a 4xx or 5xx response)
  123. * @return Generator<int, IResponse>
  124. */
  125. protected function runHEAD(string $url, bool $ignoreSSL = true, bool $httpErrors = true): Generator {
  126. return $this->runRequest('HEAD', $url, ['ignoreSSL' => $ignoreSSL, 'httpErrors' => $httpErrors]);
  127. }
  128. protected function getRequestOptions(bool $ignoreSSL, bool $httpErrors): array {
  129. $requestOptions = [
  130. 'connect_timeout' => 10,
  131. 'http_errors' => $httpErrors,
  132. 'nextcloud' => [
  133. 'allow_local_address' => true,
  134. ],
  135. ];
  136. if ($ignoreSSL) {
  137. $requestOptions['verify'] = false;
  138. }
  139. return $requestOptions;
  140. }
  141. }