CheckSetupController.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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 < 70400;
  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. } elseif ($this->iniGetWrapper->getBool('opcache.file_cache_only')) {
  459. $recommendations[] = $this->l10n->t('The shared memory based OPcache is disabled. For better performance, it is recommended to apply <code>opcache.file_cache_only=0</code> to your PHP configuration and use the file cache as second level cache only.');
  460. } else {
  461. // Check whether opcache_get_status has been explicitly disabled an in case skip usage based checks
  462. $disabledFunctions = $this->iniGetWrapper->getString('disable_functions');
  463. if (isset($disabledFunctions) && str_contains($disabledFunctions, 'opcache_get_status')) {
  464. return [];
  465. }
  466. $status = opcache_get_status(false);
  467. // Recommend to raise value, if more than 90% of max value is reached
  468. if (
  469. empty($status['opcache_statistics']['max_cached_keys']) ||
  470. ($status['opcache_statistics']['num_cached_keys'] / $status['opcache_statistics']['max_cached_keys'] > 0.9)
  471. ) {
  472. $recommendations[] = $this->l10n->t('The maximum number of OPcache keys is nearly exceeded. To assure that all scripts can be hold in 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')]);
  473. }
  474. if (
  475. empty($status['memory_usage']['free_memory']) ||
  476. ($status['memory_usage']['used_memory'] / $status['memory_usage']['free_memory'] > 9)
  477. ) {
  478. $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')]);
  479. }
  480. if (
  481. // Do not recommend to raise the interned strings buffer size above a quarter of the total OPcache size
  482. ($this->iniGetWrapper->getNumeric('opcache.interned_strings_buffer') < $this->iniGetWrapper->getNumeric('opcache.memory_consumption') / 4) &&
  483. (
  484. empty($status['interned_strings_usage']['free_memory']) ||
  485. ($status['interned_strings_usage']['used_memory'] / $status['interned_strings_usage']['free_memory'] > 9)
  486. )
  487. ) {
  488. $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')]);
  489. }
  490. }
  491. return $recommendations;
  492. }
  493. /**
  494. * Check if the required FreeType functions are present
  495. * @return bool
  496. */
  497. protected function hasFreeTypeSupport() {
  498. return function_exists('imagettfbbox') && function_exists('imagettftext');
  499. }
  500. protected function hasMissingIndexes(): array {
  501. $indexInfo = new MissingIndexInformation();
  502. // Dispatch event so apps can also hint for pending index updates if needed
  503. $event = new GenericEvent($indexInfo);
  504. $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
  505. return $indexInfo->getListOfMissingIndexes();
  506. }
  507. protected function hasMissingPrimaryKeys(): array {
  508. $info = new MissingPrimaryKeyInformation();
  509. // Dispatch event so apps can also hint for pending index updates if needed
  510. $event = new GenericEvent($info);
  511. $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_PRIMARY_KEYS_EVENT, $event);
  512. return $info->getListOfMissingPrimaryKeys();
  513. }
  514. protected function hasMissingColumns(): array {
  515. $indexInfo = new MissingColumnInformation();
  516. // Dispatch event so apps can also hint for pending index updates if needed
  517. $event = new GenericEvent($indexInfo);
  518. $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_COLUMNS_EVENT, $event);
  519. return $indexInfo->getListOfMissingColumns();
  520. }
  521. protected function isSqliteUsed() {
  522. return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
  523. }
  524. protected function isReadOnlyConfig(): bool {
  525. return \OC_Helper::isReadOnlyConfigEnabled();
  526. }
  527. protected function wasEmailTestSuccessful(): bool {
  528. // 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
  529. if ($this->config->getAppValue('core', 'emailTestSuccessful', '') === '' && $this->config->getSystemValue('mail_domain', '') === '') {
  530. return false;
  531. }
  532. // The mail test was unsuccessful or the config was changed using the UI without verifying with a testmail, hence return false
  533. if ($this->config->getAppValue('core', 'emailTestSuccessful', '') === '0') {
  534. return false;
  535. }
  536. return true;
  537. }
  538. protected function hasValidTransactionIsolationLevel(): bool {
  539. try {
  540. if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
  541. return true;
  542. }
  543. return $this->db->getTransactionIsolation() === TransactionIsolationLevel::READ_COMMITTED;
  544. } catch (Exception $e) {
  545. // ignore
  546. }
  547. return true;
  548. }
  549. protected function hasFileinfoInstalled(): bool {
  550. return \OC_Util::fileInfoLoaded();
  551. }
  552. protected function hasWorkingFileLocking(): bool {
  553. return !($this->lockingProvider instanceof NoopLockingProvider);
  554. }
  555. protected function getSuggestedOverwriteCliURL(): string {
  556. $currentOverwriteCliUrl = $this->config->getSystemValue('overwrite.cli.url', '');
  557. $suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
  558. // Check correctness by checking if it is a valid URL
  559. if (filter_var($currentOverwriteCliUrl, FILTER_VALIDATE_URL)) {
  560. $suggestedOverwriteCliUrl = '';
  561. }
  562. return $suggestedOverwriteCliUrl;
  563. }
  564. protected function getLastCronInfo(): array {
  565. $lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
  566. return [
  567. 'diffInSeconds' => time() - $lastCronRun,
  568. 'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
  569. 'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
  570. ];
  571. }
  572. protected function getCronErrors() {
  573. $errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
  574. if (is_array($errors)) {
  575. return $errors;
  576. }
  577. return [];
  578. }
  579. private function isTemporaryDirectoryWritable(): bool {
  580. try {
  581. if (!empty($this->tempManager->getTempBaseDir())) {
  582. return true;
  583. }
  584. } catch (\Exception $e) {
  585. }
  586. return false;
  587. }
  588. /**
  589. * Iterates through the configured app roots and
  590. * tests if the subdirectories are owned by the same user than the current user.
  591. *
  592. * @return array
  593. */
  594. protected function getAppDirsWithDifferentOwner(): array {
  595. $currentUser = posix_getuid();
  596. $appDirsWithDifferentOwner = [[]];
  597. foreach (OC::$APPSROOTS as $appRoot) {
  598. if ($appRoot['writable'] === true) {
  599. $appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
  600. }
  601. }
  602. $appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
  603. sort($appDirsWithDifferentOwner);
  604. return $appDirsWithDifferentOwner;
  605. }
  606. /**
  607. * Tests if the directories for one apps directory are writable by the current user.
  608. *
  609. * @param int $currentUser The current user
  610. * @param array $appRoot The app root config
  611. * @return string[] The none writable directory paths inside the app root
  612. */
  613. private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
  614. $appDirsWithDifferentOwner = [];
  615. $appsPath = $appRoot['path'];
  616. $appsDir = new DirectoryIterator($appRoot['path']);
  617. foreach ($appsDir as $fileInfo) {
  618. if ($fileInfo->isDir() && !$fileInfo->isDot()) {
  619. $absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
  620. $appDirUser = fileowner($absAppPath);
  621. if ($appDirUser !== $currentUser) {
  622. $appDirsWithDifferentOwner[] = $absAppPath;
  623. }
  624. }
  625. }
  626. return $appDirsWithDifferentOwner;
  627. }
  628. /**
  629. * Checks for potential PHP modules that would improve the instance
  630. *
  631. * @return string[] A list of PHP modules that is recommended
  632. */
  633. protected function hasRecommendedPHPModules(): array {
  634. $recommendedPHPModules = [];
  635. if (!extension_loaded('intl')) {
  636. $recommendedPHPModules[] = 'intl';
  637. }
  638. if (!defined('PASSWORD_ARGON2I') && PHP_VERSION_ID >= 70400) {
  639. // Installing php-sodium on >=php7.4 will provide PASSWORD_ARGON2I
  640. // on previous version argon2 wasn't part of the "standard" extension
  641. // and RedHat disabled it so even installing php-sodium won't provide argon2i
  642. // support in password_hash/password_verify.
  643. $recommendedPHPModules[] = 'sodium';
  644. }
  645. return $recommendedPHPModules;
  646. }
  647. protected function isImagickEnabled(): bool {
  648. if ($this->config->getAppValue('theming', 'enabled', 'no') === 'yes') {
  649. if (!extension_loaded('imagick')) {
  650. return false;
  651. }
  652. }
  653. return true;
  654. }
  655. protected function areWebauthnExtensionsEnabled(): bool {
  656. if (!extension_loaded('bcmath')) {
  657. return false;
  658. }
  659. if (!extension_loaded('gmp')) {
  660. return false;
  661. }
  662. return true;
  663. }
  664. protected function isMysqlUsedWithoutUTF8MB4(): bool {
  665. return ($this->config->getSystemValue('dbtype', 'sqlite') === 'mysql') && ($this->config->getSystemValue('mysql.utf8mb4', false) === false);
  666. }
  667. protected function hasBigIntConversionPendingColumns(): array {
  668. // copy of ConvertFilecacheBigInt::getColumnsByTable()
  669. $tables = [
  670. 'activity' => ['activity_id', 'object_id'],
  671. 'activity_mq' => ['mail_id'],
  672. 'authtoken' => ['id'],
  673. 'bruteforce_attempts' => ['id'],
  674. 'federated_reshares' => ['share_id'],
  675. 'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart', 'mtime', 'storage_mtime'],
  676. 'filecache_extended' => ['fileid'],
  677. 'file_locks' => ['id'],
  678. 'file_metadata' => ['id'],
  679. 'jobs' => ['id'],
  680. 'mimetypes' => ['id'],
  681. 'mounts' => ['id', 'storage_id', 'root_id', 'mount_id'],
  682. 'share_external' => ['id', 'parent'],
  683. 'storages' => ['numeric_id'],
  684. ];
  685. $schema = new SchemaWrapper($this->db);
  686. $isSqlite = $this->db->getDatabasePlatform() instanceof SqlitePlatform;
  687. $pendingColumns = [];
  688. foreach ($tables as $tableName => $columns) {
  689. if (!$schema->hasTable($tableName)) {
  690. continue;
  691. }
  692. $table = $schema->getTable($tableName);
  693. foreach ($columns as $columnName) {
  694. $column = $table->getColumn($columnName);
  695. $isAutoIncrement = $column->getAutoincrement();
  696. $isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
  697. if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
  698. $pendingColumns[] = $tableName . '.' . $columnName;
  699. }
  700. }
  701. }
  702. return $pendingColumns;
  703. }
  704. protected function isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(): bool {
  705. $objectStore = $this->config->getSystemValue('objectstore', null);
  706. $objectStoreMultibucket = $this->config->getSystemValue('objectstore_multibucket', null);
  707. if (!isset($objectStoreMultibucket) && !isset($objectStore)) {
  708. return true;
  709. }
  710. if (isset($objectStoreMultibucket['class']) && $objectStoreMultibucket['class'] !== 'OC\\Files\\ObjectStore\\S3') {
  711. return true;
  712. }
  713. if (isset($objectStore['class']) && $objectStore['class'] !== 'OC\\Files\\ObjectStore\\S3') {
  714. return true;
  715. }
  716. $tempPath = sys_get_temp_dir();
  717. if (!is_dir($tempPath)) {
  718. $this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. Returned value: ' . $tempPath);
  719. return false;
  720. }
  721. $freeSpaceInTemp = function_exists('disk_free_space') ? disk_free_space($tempPath) : false;
  722. if ($freeSpaceInTemp === false) {
  723. $this->logger->error('Error while checking the available disk space of temporary PHP path or no free disk space returned. Temporary path: ' . $tempPath);
  724. return false;
  725. }
  726. $freeSpaceInTempInGB = $freeSpaceInTemp / 1024 / 1024 / 1024;
  727. if ($freeSpaceInTempInGB > 50) {
  728. return true;
  729. }
  730. $this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
  731. return false;
  732. }
  733. protected function imageMagickLacksSVGSupport(): bool {
  734. return extension_loaded('imagick') && count(\Imagick::queryFormats('SVG')) === 0;
  735. }
  736. /**
  737. * @return DataResponse
  738. * @AuthorizedAdminSetting(settings=OCA\Settings\Settings\Admin\Overview)
  739. */
  740. public function check() {
  741. $phpDefaultCharset = new PhpDefaultCharset();
  742. $phpOutputBuffering = new PhpOutputBuffering();
  743. $legacySSEKeyFormat = new LegacySSEKeyFormat($this->l10n, $this->config, $this->urlGenerator);
  744. $checkUserCertificates = new CheckUserCertificates($this->l10n, $this->config, $this->urlGenerator);
  745. $supportedDatabases = new SupportedDatabase($this->l10n, $this->connection);
  746. $ldapInvalidUuids = new LdapInvalidUuids($this->appManager, $this->l10n, $this->serverContainer);
  747. return new DataResponse(
  748. [
  749. 'isGetenvServerWorking' => !empty(getenv('PATH')),
  750. 'isReadOnlyConfig' => $this->isReadOnlyConfig(),
  751. 'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
  752. 'wasEmailTestSuccessful' => $this->wasEmailTestSuccessful(),
  753. 'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
  754. 'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
  755. 'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
  756. 'cronInfo' => $this->getLastCronInfo(),
  757. 'cronErrors' => $this->getCronErrors(),
  758. 'isFairUseOfFreePushService' => $this->isFairUseOfFreePushService(),
  759. 'serverHasInternetConnectionProblems' => $this->hasInternetConnectivityProblems(),
  760. 'isMemcacheConfigured' => $this->isMemcacheConfigured(),
  761. 'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
  762. 'isRandomnessSecure' => $this->isRandomnessSecure(),
  763. 'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
  764. 'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
  765. 'phpSupported' => $this->isPhpSupported(),
  766. 'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
  767. 'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
  768. 'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
  769. 'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
  770. 'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
  771. 'OpcacheSetupRecommendations' => $this->getOpcacheSetupRecommendations(),
  772. 'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
  773. 'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
  774. 'missingPrimaryKeys' => $this->hasMissingPrimaryKeys(),
  775. 'missingIndexes' => $this->hasMissingIndexes(),
  776. 'missingColumns' => $this->hasMissingColumns(),
  777. 'isSqliteUsed' => $this->isSqliteUsed(),
  778. 'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
  779. 'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
  780. 'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
  781. 'isImagickEnabled' => $this->isImagickEnabled(),
  782. 'areWebauthnExtensionsEnabled' => $this->areWebauthnExtensionsEnabled(),
  783. 'recommendedPHPModules' => $this->hasRecommendedPHPModules(),
  784. 'pendingBigIntConversionColumns' => $this->hasBigIntConversionPendingColumns(),
  785. 'isMysqlUsedWithoutUTF8MB4' => $this->isMysqlUsedWithoutUTF8MB4(),
  786. 'isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed' => $this->isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(),
  787. 'reverseProxyGeneratedURL' => $this->urlGenerator->getAbsoluteURL('index.php'),
  788. 'imageMagickLacksSVGSupport' => $this->imageMagickLacksSVGSupport(),
  789. PhpDefaultCharset::class => ['pass' => $phpDefaultCharset->run(), 'description' => $phpDefaultCharset->description(), 'severity' => $phpDefaultCharset->severity()],
  790. PhpOutputBuffering::class => ['pass' => $phpOutputBuffering->run(), 'description' => $phpOutputBuffering->description(), 'severity' => $phpOutputBuffering->severity()],
  791. LegacySSEKeyFormat::class => ['pass' => $legacySSEKeyFormat->run(), 'description' => $legacySSEKeyFormat->description(), 'severity' => $legacySSEKeyFormat->severity(), 'linkToDocumentation' => $legacySSEKeyFormat->linkToDocumentation()],
  792. CheckUserCertificates::class => ['pass' => $checkUserCertificates->run(), 'description' => $checkUserCertificates->description(), 'severity' => $checkUserCertificates->severity(), 'elements' => $checkUserCertificates->elements()],
  793. 'isDefaultPhoneRegionSet' => $this->config->getSystemValueString('default_phone_region', '') !== '',
  794. SupportedDatabase::class => ['pass' => $supportedDatabases->run(), 'description' => $supportedDatabases->description(), 'severity' => $supportedDatabases->severity()],
  795. 'temporaryDirectoryWritable' => $this->isTemporaryDirectoryWritable(),
  796. LdapInvalidUuids::class => ['pass' => $ldapInvalidUuids->run(), 'description' => $ldapInvalidUuids->description(), 'severity' => $ldapInvalidUuids->severity()],
  797. ]
  798. );
  799. }
  800. }