1
0

CheckSetupController.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Cthulhux <git@tuxproject.de>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author Derek <derek.kelly27@gmail.com>
  10. * @author Georg Ehrke <oc.list@georgehrke.com>
  11. * @author J0WI <J0WI@users.noreply.github.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Julius Härtl <jus@bitgrid.net>
  14. * @author Ko- <k.stoffelen@cs.ru.nl>
  15. * @author Lauris Binde <laurisb@users.noreply.github.com>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Michael Weimann <mail@michael-weimann.eu>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author nhirokinet <nhirokinet@nhiroki.net>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Sven Strickroth <email@cs-ware.de>
  24. * @author Sylvia van Os <sylvia@hackerchick.me>
  25. * @author timm2k <timm2k@gmx.de>
  26. * @author Timo Förster <tfoerster@webfoersterei.de>
  27. * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
  28. * @author MichaIng <micha@dietpi.com>
  29. *
  30. * @license AGPL-3.0
  31. *
  32. * This code is free software: you can redistribute it and/or modify
  33. * it under the terms of the GNU Affero General Public License, version 3,
  34. * as published by the Free Software Foundation.
  35. *
  36. * This program is distributed in the hope that it will be useful,
  37. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  38. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  39. * GNU Affero General Public License for more details.
  40. *
  41. * You should have received a copy of the GNU Affero General Public License, version 3,
  42. * along with this program. If not, see <http://www.gnu.org/licenses/>
  43. *
  44. */
  45. namespace OCA\Settings\Controller;
  46. use bantu\IniGetWrapper\IniGetWrapper;
  47. use DirectoryIterator;
  48. use Doctrine\DBAL\Exception;
  49. use Doctrine\DBAL\Platforms\SqlitePlatform;
  50. use Doctrine\DBAL\TransactionIsolationLevel;
  51. use GuzzleHttp\Exception\ClientException;
  52. use OC;
  53. use OC\AppFramework\Http;
  54. use OC\DB\Connection;
  55. use OC\DB\MissingColumnInformation;
  56. use OC\DB\MissingIndexInformation;
  57. use OC\DB\MissingPrimaryKeyInformation;
  58. use OC\DB\SchemaWrapper;
  59. use OC\IntegrityCheck\Checker;
  60. use OC\Lock\NoopLockingProvider;
  61. use OC\MemoryInfo;
  62. use OCA\Settings\SetupChecks\CheckUserCertificates;
  63. use OCA\Settings\SetupChecks\LdapInvalidUuids;
  64. use OCA\Settings\SetupChecks\LegacySSEKeyFormat;
  65. use OCA\Settings\SetupChecks\PhpDefaultCharset;
  66. use OCA\Settings\SetupChecks\PhpOutputBuffering;
  67. use OCA\Settings\SetupChecks\SupportedDatabase;
  68. use OCP\App\IAppManager;
  69. use OCP\AppFramework\Controller;
  70. use OCP\AppFramework\Http\DataDisplayResponse;
  71. use OCP\AppFramework\Http\DataResponse;
  72. use OCP\AppFramework\Http\RedirectResponse;
  73. use OCP\DB\Types;
  74. use OCP\Http\Client\IClientService;
  75. use OCP\IConfig;
  76. use OCP\IDateTimeFormatter;
  77. use OCP\IDBConnection;
  78. use OCP\IL10N;
  79. use OCP\IRequest;
  80. use OCP\IServerContainer;
  81. use OCP\ITempManager;
  82. use OCP\IURLGenerator;
  83. use OCP\Lock\ILockingProvider;
  84. use OCP\Notification\IManager;
  85. use OCP\Security\ISecureRandom;
  86. use Psr\Log\LoggerInterface;
  87. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  88. use Symfony\Component\EventDispatcher\GenericEvent;
  89. class CheckSetupController extends Controller {
  90. /** @var IConfig */
  91. private $config;
  92. /** @var IClientService */
  93. private $clientService;
  94. /** @var IURLGenerator */
  95. private $urlGenerator;
  96. /** @var IL10N */
  97. private $l10n;
  98. /** @var Checker */
  99. private $checker;
  100. /** @var LoggerInterface */
  101. private $logger;
  102. /** @var EventDispatcherInterface */
  103. private $dispatcher;
  104. /** @var Connection */
  105. private $db;
  106. /** @var ILockingProvider */
  107. private $lockingProvider;
  108. /** @var IDateTimeFormatter */
  109. private $dateTimeFormatter;
  110. /** @var MemoryInfo */
  111. private $memoryInfo;
  112. /** @var ISecureRandom */
  113. private $secureRandom;
  114. /** @var IniGetWrapper */
  115. private $iniGetWrapper;
  116. /** @var IDBConnection */
  117. private $connection;
  118. /** @var ITempManager */
  119. private $tempManager;
  120. /** @var IManager */
  121. private $manager;
  122. /** @var IAppManager */
  123. private $appManager;
  124. /** @var IServerContainer */
  125. private $serverContainer;
  126. public function __construct($AppName,
  127. IRequest $request,
  128. IConfig $config,
  129. IClientService $clientService,
  130. IURLGenerator $urlGenerator,
  131. IL10N $l10n,
  132. Checker $checker,
  133. LoggerInterface $logger,
  134. EventDispatcherInterface $dispatcher,
  135. Connection $db,
  136. ILockingProvider $lockingProvider,
  137. IDateTimeFormatter $dateTimeFormatter,
  138. MemoryInfo $memoryInfo,
  139. ISecureRandom $secureRandom,
  140. IniGetWrapper $iniGetWrapper,
  141. IDBConnection $connection,
  142. ITempManager $tempManager,
  143. IManager $manager,
  144. IAppManager $appManager,
  145. IServerContainer $serverContainer
  146. ) {
  147. parent::__construct($AppName, $request);
  148. $this->config = $config;
  149. $this->clientService = $clientService;
  150. $this->urlGenerator = $urlGenerator;
  151. $this->l10n = $l10n;
  152. $this->checker = $checker;
  153. $this->logger = $logger;
  154. $this->dispatcher = $dispatcher;
  155. $this->db = $db;
  156. $this->lockingProvider = $lockingProvider;
  157. $this->dateTimeFormatter = $dateTimeFormatter;
  158. $this->memoryInfo = $memoryInfo;
  159. $this->secureRandom = $secureRandom;
  160. $this->iniGetWrapper = $iniGetWrapper;
  161. $this->connection = $connection;
  162. $this->tempManager = $tempManager;
  163. $this->manager = $manager;
  164. $this->appManager = $appManager;
  165. $this->serverContainer = $serverContainer;
  166. }
  167. /**
  168. * Check if is fair use of free push service
  169. * @return bool
  170. */
  171. private function isFairUseOfFreePushService(): bool {
  172. return $this->manager->isFairUseOfFreePushService();
  173. }
  174. /**
  175. * Checks if the server can connect to the internet using HTTPS and HTTP
  176. * @return bool
  177. */
  178. private function hasInternetConnectivityProblems(): bool {
  179. if ($this->config->getSystemValue('has_internet_connection', true) === false) {
  180. return false;
  181. }
  182. $siteArray = $this->config->getSystemValue('connectivity_check_domains', [
  183. 'www.nextcloud.com', 'www.startpage.com', 'www.eff.org', 'www.edri.org'
  184. ]);
  185. foreach ($siteArray as $site) {
  186. if ($this->isSiteReachable($site)) {
  187. return false;
  188. }
  189. }
  190. return true;
  191. }
  192. /**
  193. * Checks if the Nextcloud server can connect to a specific URL
  194. * @param string $site site domain or full URL with http/https protocol
  195. * @return bool
  196. */
  197. private function isSiteReachable(string $site): bool {
  198. try {
  199. $client = $this->clientService->newClient();
  200. // if there is no protocol, test http:// AND https://
  201. if (preg_match('/^https?:\/\//', $site) !== 1) {
  202. $httpSite = 'http://' . $site . '/';
  203. $client->get($httpSite);
  204. $httpsSite = 'https://' . $site . '/';
  205. $client->get($httpsSite);
  206. } else {
  207. $client->get($site);
  208. }
  209. } catch (\Exception $e) {
  210. $this->logger->error('Cannot connect to: ' . $site, [
  211. 'app' => 'internet_connection_check',
  212. 'exception' => $e,
  213. ]);
  214. return false;
  215. }
  216. return true;
  217. }
  218. /**
  219. * Checks whether a local memcache is installed or not
  220. * @return bool
  221. */
  222. private function isMemcacheConfigured() {
  223. return $this->config->getSystemValue('memcache.local', null) !== null;
  224. }
  225. /**
  226. * Whether PHP can generate "secure" pseudorandom integers
  227. *
  228. * @return bool
  229. */
  230. private function isRandomnessSecure() {
  231. try {
  232. $this->secureRandom->generate(1);
  233. } catch (\Exception $ex) {
  234. return false;
  235. }
  236. return true;
  237. }
  238. /**
  239. * Public for the sake of unit-testing
  240. *
  241. * @return array
  242. */
  243. protected function getCurlVersion() {
  244. return curl_version();
  245. }
  246. /**
  247. * Check if the used SSL lib is outdated. Older OpenSSL and NSS versions do
  248. * have multiple bugs which likely lead to problems in combination with
  249. * functionality required by ownCloud such as SNI.
  250. *
  251. * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
  252. * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
  253. * @return string
  254. */
  255. private function isUsedTlsLibOutdated() {
  256. // Don't run check when:
  257. // 1. Server has `has_internet_connection` set to false
  258. // 2. AppStore AND S2S is disabled
  259. if (!$this->config->getSystemValue('has_internet_connection', true)) {
  260. return '';
  261. }
  262. if (!$this->config->getSystemValue('appstoreenabled', true)
  263. && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
  264. && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
  265. return '';
  266. }
  267. $versionString = $this->getCurlVersion();
  268. if (isset($versionString['ssl_version'])) {
  269. $versionString = $versionString['ssl_version'];
  270. } else {
  271. return '';
  272. }
  273. $features = $this->l10n->t('installing and updating apps via the App Store or Federated Cloud Sharing');
  274. if (!$this->config->getSystemValue('appstoreenabled', true)) {
  275. $features = $this->l10n->t('Federated Cloud Sharing');
  276. }
  277. // Check if at least OpenSSL after 1.01d or 1.0.2b
  278. if (strpos($versionString, 'OpenSSL/') === 0) {
  279. $majorVersion = substr($versionString, 8, 5);
  280. $patchRelease = substr($versionString, 13, 6);
  281. if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
  282. ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
  283. return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]);
  284. }
  285. }
  286. // Check if NSS and perform heuristic check
  287. if (strpos($versionString, 'NSS/') === 0) {
  288. try {
  289. $firstClient = $this->clientService->newClient();
  290. $firstClient->get('https://nextcloud.com/');
  291. $secondClient = $this->clientService->newClient();
  292. $secondClient->get('https://nextcloud.com/');
  293. } catch (ClientException $e) {
  294. if ($e->getResponse()->getStatusCode() === 400) {
  295. return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]);
  296. }
  297. } catch (\Exception $e) {
  298. $this->logger->warning('error checking curl', [
  299. 'app' => 'settings',
  300. 'exception' => $e,
  301. ]);
  302. return $this->l10n->t('Could not determine if TLS version of cURL is outdated or not because an error happened during the HTTPS request against https://nextcloud.com. Please check the Nextcloud log file for more details.');
  303. }
  304. }
  305. return '';
  306. }
  307. /**
  308. * Whether the version is outdated
  309. *
  310. * @return bool
  311. */
  312. protected function isPhpOutdated(): bool {
  313. return PHP_VERSION_ID < 80000;
  314. }
  315. /**
  316. * Whether the php version is still supported (at time of release)
  317. * according to: https://www.php.net/supported-versions.php
  318. *
  319. * @return array
  320. */
  321. private function isPhpSupported(): array {
  322. return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
  323. }
  324. /**
  325. * Check if the reverse proxy configuration is working as expected
  326. *
  327. * @return bool
  328. */
  329. private function forwardedForHeadersWorking(): bool {
  330. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  331. $remoteAddress = $this->request->getHeader('REMOTE_ADDR');
  332. if (empty($trustedProxies) && $this->request->getHeader('X-Forwarded-Host') !== '') {
  333. return false;
  334. }
  335. if (\is_array($trustedProxies)) {
  336. if (\in_array($remoteAddress, $trustedProxies, true) && $remoteAddress !== '127.0.0.1') {
  337. return $remoteAddress !== $this->request->getRemoteAddress();
  338. }
  339. } else {
  340. return false;
  341. }
  342. // either not enabled or working correctly
  343. return true;
  344. }
  345. /**
  346. * Checks if the correct memcache module for PHP is installed. Only
  347. * fails if memcached is configured and the working module is not installed.
  348. *
  349. * @return bool
  350. */
  351. private function isCorrectMemcachedPHPModuleInstalled() {
  352. if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
  353. return true;
  354. }
  355. // there are two different memcache modules for PHP
  356. // we only support memcached and not memcache
  357. // https://code.google.com/p/memcached/wiki/PHPClientComparison
  358. return !(!extension_loaded('memcached') && extension_loaded('memcache'));
  359. }
  360. /**
  361. * Checks if set_time_limit is not disabled.
  362. *
  363. * @return bool
  364. */
  365. private function isSettimelimitAvailable() {
  366. if (function_exists('set_time_limit')
  367. && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
  368. return true;
  369. }
  370. return false;
  371. }
  372. /**
  373. * @return RedirectResponse
  374. * @AuthorizedAdminSetting(settings=OCA\Settings\Settings\Admin\Overview)
  375. */
  376. public function rescanFailedIntegrityCheck(): RedirectResponse {
  377. $this->checker->runInstanceVerification();
  378. return new RedirectResponse(
  379. $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'overview'])
  380. );
  381. }
  382. /**
  383. * @NoCSRFRequired
  384. * @AuthorizedAdminSetting(settings=OCA\Settings\Settings\Admin\Overview)
  385. */
  386. public function getFailedIntegrityCheckFiles(): DataDisplayResponse {
  387. if (!$this->checker->isCodeCheckEnforced()) {
  388. return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
  389. }
  390. $completeResults = $this->checker->getResults();
  391. if (!empty($completeResults)) {
  392. $formattedTextResponse = 'Technical information
  393. =====================
  394. The following list covers which files have failed the integrity check. Please read
  395. the previous linked documentation to learn more about the errors and how to fix
  396. them.
  397. Results
  398. =======
  399. ';
  400. foreach ($completeResults as $context => $contextResult) {
  401. $formattedTextResponse .= "- $context\n";
  402. foreach ($contextResult as $category => $result) {
  403. $formattedTextResponse .= "\t- $category\n";
  404. if ($category !== 'EXCEPTION') {
  405. foreach ($result as $key => $results) {
  406. $formattedTextResponse .= "\t\t- $key\n";
  407. }
  408. } else {
  409. foreach ($result as $key => $results) {
  410. $formattedTextResponse .= "\t\t- $results\n";
  411. }
  412. }
  413. }
  414. }
  415. $formattedTextResponse .= '
  416. Raw output
  417. ==========
  418. ';
  419. $formattedTextResponse .= print_r($completeResults, true);
  420. } else {
  421. $formattedTextResponse = 'No errors have been found.';
  422. }
  423. return new DataDisplayResponse(
  424. $formattedTextResponse,
  425. Http::STATUS_OK,
  426. [
  427. 'Content-Type' => 'text/plain',
  428. ]
  429. );
  430. }
  431. /**
  432. * Checks whether a PHP OPcache is properly set up
  433. * @return string[] The list of OPcache setup recommendations
  434. */
  435. protected function getOpcacheSetupRecommendations(): array {
  436. // If the module is not loaded, return directly to skip inapplicable checks
  437. if (!extension_loaded('Zend OPcache')) {
  438. return [$this->l10n->t('The PHP OPcache module is not loaded. For better performance it is recommended to load it into your PHP installation.')];
  439. }
  440. $recommendations = [];
  441. // Check whether Nextcloud is allowed to use the OPcache API
  442. $isPermitted = true;
  443. $permittedPath = $this->iniGetWrapper->getString('opcache.restrict_api');
  444. if (isset($permittedPath) && $permittedPath !== '' && !str_starts_with(\OC::$SERVERROOT, rtrim($permittedPath, '/'))) {
  445. $isPermitted = false;
  446. }
  447. if (!$this->iniGetWrapper->getBool('opcache.enable')) {
  448. $recommendations[] = $this->l10n->t('OPcache is disabled. For better performance, it is recommended to apply <code>opcache.enable=1</code> to your PHP configuration.');
  449. // Check for saved comments only when OPcache is currently disabled. If it was enabled, opcache.save_comments=0 would break Nextcloud in the first place.
  450. if (!$this->iniGetWrapper->getBool('opcache.save_comments')) {
  451. $recommendations[] = $this->l10n->t('OPcache is configured to remove code comments. With OPcache enabled, <code>opcache.save_comments=1</code> must be set for Nextcloud to function.');
  452. }
  453. if (!$isPermitted) {
  454. $recommendations[] = $this->l10n->t('Nextcloud is not allowed to use the OPcache API. With OPcache enabled, it is highly recommended to include all Nextcloud directories with <code>opcache.restrict_api</code> or unset this setting to disable OPcache API restrictions, to prevent errors during Nextcloud core or app upgrades.');
  455. }
  456. } elseif (!$isPermitted) {
  457. $recommendations[] = $this->l10n->t('Nextcloud is not allowed to use the OPcache API. It is highly recommended to include all Nextcloud directories with <code>opcache.restrict_api</code> or unset this setting to disable OPcache API restrictions, to prevent errors during Nextcloud core or app upgrades.');
  458. } else {
  459. // Check whether opcache_get_status has been explicitly disabled an in case skip usage based checks
  460. $disabledFunctions = $this->iniGetWrapper->getString('disable_functions');
  461. if (isset($disabledFunctions) && str_contains($disabledFunctions, 'opcache_get_status')) {
  462. return [];
  463. }
  464. $status = opcache_get_status(false);
  465. // Recommend to raise value, if more than 90% of max value is reached
  466. if (
  467. empty($status['opcache_statistics']['max_cached_keys']) ||
  468. ($status['opcache_statistics']['num_cached_keys'] / $status['opcache_statistics']['max_cached_keys'] > 0.9)
  469. ) {
  470. $recommendations[] = $this->l10n->t('The maximum number of OPcache keys is nearly exceeded. To assure that all scripts can be kept in the cache, it is recommended to apply <code>opcache.max_accelerated_files</code> to your PHP configuration with a value higher than <code>%s</code>.', [($this->iniGetWrapper->getNumeric('opcache.max_accelerated_files') ?: 'currently')]);
  471. }
  472. if (
  473. empty($status['memory_usage']['free_memory']) ||
  474. ($status['memory_usage']['used_memory'] / $status['memory_usage']['free_memory'] > 9)
  475. ) {
  476. $recommendations[] = $this->l10n->t('The OPcache buffer is nearly full. To assure that all scripts can be hold in cache, it is recommended to apply <code>opcache.memory_consumption</code> to your PHP configuration with a value higher than <code>%s</code>.', [($this->iniGetWrapper->getNumeric('opcache.memory_consumption') ?: 'currently')]);
  477. }
  478. if (
  479. empty($status['interned_strings_usage']['free_memory']) ||
  480. (
  481. ($status['interned_strings_usage']['used_memory'] / $status['interned_strings_usage']['free_memory'] > 9) &&
  482. // Do not recommend to raise the interned strings buffer size above a quarter of the total OPcache size
  483. ($this->iniGetWrapper->getNumeric('opcache.interned_strings_buffer') < $this->iniGetWrapper->getNumeric('opcache.memory_consumption') / 4)
  484. )
  485. ) {
  486. $recommendations[] = $this->l10n->t('The OPcache interned strings buffer is nearly full. To assure that repeating strings can be effectively cached, it is recommended to apply <code>opcache.interned_strings_buffer</code> to your PHP configuration with a value higher than <code>%s</code>.', [($this->iniGetWrapper->getNumeric('opcache.interned_strings_buffer') ?: 'currently')]);
  487. }
  488. }
  489. return $recommendations;
  490. }
  491. /**
  492. * Check if the required FreeType functions are present
  493. * @return bool
  494. */
  495. protected function hasFreeTypeSupport() {
  496. return function_exists('imagettfbbox') && function_exists('imagettftext');
  497. }
  498. protected function hasMissingIndexes(): array {
  499. $indexInfo = new MissingIndexInformation();
  500. // Dispatch event so apps can also hint for pending index updates if needed
  501. $event = new GenericEvent($indexInfo);
  502. $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
  503. return $indexInfo->getListOfMissingIndexes();
  504. }
  505. protected function hasMissingPrimaryKeys(): array {
  506. $info = new MissingPrimaryKeyInformation();
  507. // Dispatch event so apps can also hint for pending index updates if needed
  508. $event = new GenericEvent($info);
  509. $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_PRIMARY_KEYS_EVENT, $event);
  510. return $info->getListOfMissingPrimaryKeys();
  511. }
  512. protected function hasMissingColumns(): array {
  513. $indexInfo = new MissingColumnInformation();
  514. // Dispatch event so apps can also hint for pending index updates if needed
  515. $event = new GenericEvent($indexInfo);
  516. $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_COLUMNS_EVENT, $event);
  517. return $indexInfo->getListOfMissingColumns();
  518. }
  519. protected function isSqliteUsed() {
  520. return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
  521. }
  522. protected function isReadOnlyConfig(): bool {
  523. return \OC_Helper::isReadOnlyConfigEnabled();
  524. }
  525. protected function wasEmailTestSuccessful(): bool {
  526. // Handle the case that the configuration was set before the check was introduced or it was only set via command line and not from the UI
  527. if ($this->config->getAppValue('core', 'emailTestSuccessful', '') === '' && $this->config->getSystemValue('mail_domain', '') === '') {
  528. return false;
  529. }
  530. // The mail test was unsuccessful or the config was changed using the UI without verifying with a testmail, hence return false
  531. if ($this->config->getAppValue('core', 'emailTestSuccessful', '') === '0') {
  532. return false;
  533. }
  534. return true;
  535. }
  536. protected function hasValidTransactionIsolationLevel(): bool {
  537. try {
  538. if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
  539. return true;
  540. }
  541. return $this->db->getTransactionIsolation() === TransactionIsolationLevel::READ_COMMITTED;
  542. } catch (Exception $e) {
  543. // ignore
  544. }
  545. return true;
  546. }
  547. protected function hasFileinfoInstalled(): bool {
  548. return \OC_Util::fileInfoLoaded();
  549. }
  550. protected function hasWorkingFileLocking(): bool {
  551. return !($this->lockingProvider instanceof NoopLockingProvider);
  552. }
  553. protected function getSuggestedOverwriteCliURL(): string {
  554. $currentOverwriteCliUrl = $this->config->getSystemValue('overwrite.cli.url', '');
  555. $suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
  556. // Check correctness by checking if it is a valid URL
  557. if (filter_var($currentOverwriteCliUrl, FILTER_VALIDATE_URL)) {
  558. $suggestedOverwriteCliUrl = '';
  559. }
  560. return $suggestedOverwriteCliUrl;
  561. }
  562. protected function getLastCronInfo(): array {
  563. $lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
  564. return [
  565. 'diffInSeconds' => time() - $lastCronRun,
  566. 'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
  567. 'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
  568. ];
  569. }
  570. protected function getCronErrors() {
  571. $errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
  572. if (is_array($errors)) {
  573. return $errors;
  574. }
  575. return [];
  576. }
  577. private function isTemporaryDirectoryWritable(): bool {
  578. try {
  579. if (!empty($this->tempManager->getTempBaseDir())) {
  580. return true;
  581. }
  582. } catch (\Exception $e) {
  583. }
  584. return false;
  585. }
  586. /**
  587. * Iterates through the configured app roots and
  588. * tests if the subdirectories are owned by the same user than the current user.
  589. *
  590. * @return array
  591. */
  592. protected function getAppDirsWithDifferentOwner(): array {
  593. $currentUser = posix_getuid();
  594. $appDirsWithDifferentOwner = [[]];
  595. foreach (OC::$APPSROOTS as $appRoot) {
  596. if ($appRoot['writable'] === true) {
  597. $appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
  598. }
  599. }
  600. $appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
  601. sort($appDirsWithDifferentOwner);
  602. return $appDirsWithDifferentOwner;
  603. }
  604. /**
  605. * Tests if the directories for one apps directory are writable by the current user.
  606. *
  607. * @param int $currentUser The current user
  608. * @param array $appRoot The app root config
  609. * @return string[] The none writable directory paths inside the app root
  610. */
  611. private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
  612. $appDirsWithDifferentOwner = [];
  613. $appsPath = $appRoot['path'];
  614. $appsDir = new DirectoryIterator($appRoot['path']);
  615. foreach ($appsDir as $fileInfo) {
  616. if ($fileInfo->isDir() && !$fileInfo->isDot()) {
  617. $absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
  618. $appDirUser = fileowner($absAppPath);
  619. if ($appDirUser !== $currentUser) {
  620. $appDirsWithDifferentOwner[] = $absAppPath;
  621. }
  622. }
  623. }
  624. return $appDirsWithDifferentOwner;
  625. }
  626. /**
  627. * Checks for potential PHP modules that would improve the instance
  628. *
  629. * @return string[] A list of PHP modules that is recommended
  630. */
  631. protected function hasRecommendedPHPModules(): array {
  632. $recommendedPHPModules = [];
  633. if (!extension_loaded('intl')) {
  634. $recommendedPHPModules[] = 'intl';
  635. }
  636. if (!extension_loaded('sysvsem')) {
  637. // used to limit the usage of resources by preview generator
  638. $recommendedPHPModules[] = 'sysvsem';
  639. }
  640. if (!defined('PASSWORD_ARGON2I') && PHP_VERSION_ID >= 70400) {
  641. // Installing php-sodium on >=php7.4 will provide PASSWORD_ARGON2I
  642. // on previous version argon2 wasn't part of the "standard" extension
  643. // and RedHat disabled it so even installing php-sodium won't provide argon2i
  644. // support in password_hash/password_verify.
  645. $recommendedPHPModules[] = 'sodium';
  646. }
  647. return $recommendedPHPModules;
  648. }
  649. protected function isImagickEnabled(): bool {
  650. if ($this->config->getAppValue('theming', 'enabled', 'no') === 'yes') {
  651. if (!extension_loaded('imagick')) {
  652. return false;
  653. }
  654. }
  655. return true;
  656. }
  657. protected function areWebauthnExtensionsEnabled(): bool {
  658. if (!extension_loaded('bcmath')) {
  659. return false;
  660. }
  661. if (!extension_loaded('gmp')) {
  662. return false;
  663. }
  664. return true;
  665. }
  666. protected function is64bit(): bool {
  667. if (PHP_INT_SIZE < 8) {
  668. return false;
  669. } else {
  670. return true;
  671. }
  672. }
  673. protected function isMysqlUsedWithoutUTF8MB4(): bool {
  674. return ($this->config->getSystemValue('dbtype', 'sqlite') === 'mysql') && ($this->config->getSystemValue('mysql.utf8mb4', false) === false);
  675. }
  676. protected function hasBigIntConversionPendingColumns(): array {
  677. // copy of ConvertFilecacheBigInt::getColumnsByTable()
  678. $tables = [
  679. 'activity' => ['activity_id', 'object_id'],
  680. 'activity_mq' => ['mail_id'],
  681. 'authtoken' => ['id'],
  682. 'bruteforce_attempts' => ['id'],
  683. 'federated_reshares' => ['share_id'],
  684. 'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart', 'mtime', 'storage_mtime'],
  685. 'filecache_extended' => ['fileid'],
  686. 'files_trash' => ['auto_id'],
  687. 'file_locks' => ['id'],
  688. 'file_metadata' => ['id'],
  689. 'jobs' => ['id'],
  690. 'mimetypes' => ['id'],
  691. 'mounts' => ['id', 'storage_id', 'root_id', 'mount_id'],
  692. 'share_external' => ['id', 'parent'],
  693. 'storages' => ['numeric_id'],
  694. ];
  695. $schema = new SchemaWrapper($this->db);
  696. $isSqlite = $this->db->getDatabasePlatform() instanceof SqlitePlatform;
  697. $pendingColumns = [];
  698. foreach ($tables as $tableName => $columns) {
  699. if (!$schema->hasTable($tableName)) {
  700. continue;
  701. }
  702. $table = $schema->getTable($tableName);
  703. foreach ($columns as $columnName) {
  704. $column = $table->getColumn($columnName);
  705. $isAutoIncrement = $column->getAutoincrement();
  706. $isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
  707. if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
  708. $pendingColumns[] = $tableName . '.' . $columnName;
  709. }
  710. }
  711. }
  712. return $pendingColumns;
  713. }
  714. protected function isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(): bool {
  715. $objectStore = $this->config->getSystemValue('objectstore', null);
  716. $objectStoreMultibucket = $this->config->getSystemValue('objectstore_multibucket', null);
  717. if (!isset($objectStoreMultibucket) && !isset($objectStore)) {
  718. return true;
  719. }
  720. if (isset($objectStoreMultibucket['class']) && $objectStoreMultibucket['class'] !== 'OC\\Files\\ObjectStore\\S3') {
  721. return true;
  722. }
  723. if (isset($objectStore['class']) && $objectStore['class'] !== 'OC\\Files\\ObjectStore\\S3') {
  724. return true;
  725. }
  726. $tempPath = sys_get_temp_dir();
  727. if (!is_dir($tempPath)) {
  728. $this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. Returned value: ' . $tempPath);
  729. return false;
  730. }
  731. $freeSpaceInTemp = function_exists('disk_free_space') ? disk_free_space($tempPath) : false;
  732. if ($freeSpaceInTemp === false) {
  733. $this->logger->error('Error while checking the available disk space of temporary PHP path or no free disk space returned. Temporary path: ' . $tempPath);
  734. return false;
  735. }
  736. $freeSpaceInTempInGB = $freeSpaceInTemp / 1024 / 1024 / 1024;
  737. if ($freeSpaceInTempInGB > 50) {
  738. return true;
  739. }
  740. $this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
  741. return false;
  742. }
  743. protected function imageMagickLacksSVGSupport(): bool {
  744. return extension_loaded('imagick') && count(\Imagick::queryFormats('SVG')) === 0;
  745. }
  746. /**
  747. * @return DataResponse
  748. * @AuthorizedAdminSetting(settings=OCA\Settings\Settings\Admin\Overview)
  749. */
  750. public function check() {
  751. $phpDefaultCharset = new PhpDefaultCharset();
  752. $phpOutputBuffering = new PhpOutputBuffering();
  753. $legacySSEKeyFormat = new LegacySSEKeyFormat($this->l10n, $this->config, $this->urlGenerator);
  754. $checkUserCertificates = new CheckUserCertificates($this->l10n, $this->config, $this->urlGenerator);
  755. $supportedDatabases = new SupportedDatabase($this->l10n, $this->connection);
  756. $ldapInvalidUuids = new LdapInvalidUuids($this->appManager, $this->l10n, $this->serverContainer);
  757. return new DataResponse(
  758. [
  759. 'isGetenvServerWorking' => !empty(getenv('PATH')),
  760. 'isReadOnlyConfig' => $this->isReadOnlyConfig(),
  761. 'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
  762. 'wasEmailTestSuccessful' => $this->wasEmailTestSuccessful(),
  763. 'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
  764. 'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
  765. 'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
  766. 'cronInfo' => $this->getLastCronInfo(),
  767. 'cronErrors' => $this->getCronErrors(),
  768. 'isFairUseOfFreePushService' => $this->isFairUseOfFreePushService(),
  769. 'serverHasInternetConnectionProblems' => $this->hasInternetConnectivityProblems(),
  770. 'isMemcacheConfigured' => $this->isMemcacheConfigured(),
  771. 'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
  772. 'isRandomnessSecure' => $this->isRandomnessSecure(),
  773. 'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
  774. 'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
  775. 'phpSupported' => $this->isPhpSupported(),
  776. 'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
  777. 'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
  778. 'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
  779. 'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
  780. 'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
  781. 'OpcacheSetupRecommendations' => $this->getOpcacheSetupRecommendations(),
  782. 'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
  783. 'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
  784. 'missingPrimaryKeys' => $this->hasMissingPrimaryKeys(),
  785. 'missingIndexes' => $this->hasMissingIndexes(),
  786. 'missingColumns' => $this->hasMissingColumns(),
  787. 'isSqliteUsed' => $this->isSqliteUsed(),
  788. 'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
  789. 'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
  790. 'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
  791. 'isImagickEnabled' => $this->isImagickEnabled(),
  792. 'areWebauthnExtensionsEnabled' => $this->areWebauthnExtensionsEnabled(),
  793. 'is64bit' => $this->is64bit(),
  794. 'recommendedPHPModules' => $this->hasRecommendedPHPModules(),
  795. 'pendingBigIntConversionColumns' => $this->hasBigIntConversionPendingColumns(),
  796. 'isMysqlUsedWithoutUTF8MB4' => $this->isMysqlUsedWithoutUTF8MB4(),
  797. 'isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed' => $this->isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(),
  798. 'reverseProxyGeneratedURL' => $this->urlGenerator->getAbsoluteURL('index.php'),
  799. 'imageMagickLacksSVGSupport' => $this->imageMagickLacksSVGSupport(),
  800. PhpDefaultCharset::class => ['pass' => $phpDefaultCharset->run(), 'description' => $phpDefaultCharset->description(), 'severity' => $phpDefaultCharset->severity()],
  801. PhpOutputBuffering::class => ['pass' => $phpOutputBuffering->run(), 'description' => $phpOutputBuffering->description(), 'severity' => $phpOutputBuffering->severity()],
  802. LegacySSEKeyFormat::class => ['pass' => $legacySSEKeyFormat->run(), 'description' => $legacySSEKeyFormat->description(), 'severity' => $legacySSEKeyFormat->severity(), 'linkToDocumentation' => $legacySSEKeyFormat->linkToDocumentation()],
  803. CheckUserCertificates::class => ['pass' => $checkUserCertificates->run(), 'description' => $checkUserCertificates->description(), 'severity' => $checkUserCertificates->severity(), 'elements' => $checkUserCertificates->elements()],
  804. 'isDefaultPhoneRegionSet' => $this->config->getSystemValueString('default_phone_region', '') !== '',
  805. SupportedDatabase::class => ['pass' => $supportedDatabases->run(), 'description' => $supportedDatabases->description(), 'severity' => $supportedDatabases->severity()],
  806. 'temporaryDirectoryWritable' => $this->isTemporaryDirectoryWritable(),
  807. LdapInvalidUuids::class => ['pass' => $ldapInvalidUuids->run(), 'description' => $ldapInvalidUuids->description(), 'severity' => $ldapInvalidUuids->severity()],
  808. ]
  809. );
  810. }
  811. }