Setup.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC;
  9. use bantu\IniGetWrapper\IniGetWrapper;
  10. use Exception;
  11. use InvalidArgumentException;
  12. use OC\Authentication\Token\PublicKeyTokenProvider;
  13. use OC\Authentication\Token\TokenCleanupJob;
  14. use OC\Log\Rotate;
  15. use OC\Preview\BackgroundCleanupJob;
  16. use OC\TextProcessing\RemoveOldTasksBackgroundJob;
  17. use OC\User\BackgroundJobs\CleanupDeletedUsers;
  18. use OCP\AppFramework\Utility\ITimeFactory;
  19. use OCP\BackgroundJob\IJobList;
  20. use OCP\Defaults;
  21. use OCP\IAppConfig;
  22. use OCP\IConfig;
  23. use OCP\IGroup;
  24. use OCP\IGroupManager;
  25. use OCP\IL10N;
  26. use OCP\IRequest;
  27. use OCP\IUserManager;
  28. use OCP\IUserSession;
  29. use OCP\L10N\IFactory as IL10NFactory;
  30. use OCP\Migration\IOutput;
  31. use OCP\Security\ISecureRandom;
  32. use OCP\Server;
  33. use OCP\ServerVersion;
  34. use Psr\Log\LoggerInterface;
  35. class Setup {
  36. protected IL10N $l10n;
  37. public function __construct(
  38. protected SystemConfig $config,
  39. protected IniGetWrapper $iniWrapper,
  40. IL10NFactory $l10nFactory,
  41. protected Defaults $defaults,
  42. protected LoggerInterface $logger,
  43. protected ISecureRandom $random,
  44. protected Installer $installer,
  45. ) {
  46. $this->l10n = $l10nFactory->get('lib');
  47. }
  48. protected static array $dbSetupClasses = [
  49. 'mysql' => \OC\Setup\MySQL::class,
  50. 'pgsql' => \OC\Setup\PostgreSQL::class,
  51. 'oci' => \OC\Setup\OCI::class,
  52. 'sqlite' => \OC\Setup\Sqlite::class,
  53. 'sqlite3' => \OC\Setup\Sqlite::class,
  54. ];
  55. /**
  56. * Wrapper around the "class_exists" PHP function to be able to mock it
  57. */
  58. protected function class_exists(string $name): bool {
  59. return class_exists($name);
  60. }
  61. /**
  62. * Wrapper around the "is_callable" PHP function to be able to mock it
  63. */
  64. protected function is_callable(string $name): bool {
  65. return is_callable($name);
  66. }
  67. /**
  68. * Wrapper around \PDO::getAvailableDrivers
  69. */
  70. protected function getAvailableDbDriversForPdo(): array {
  71. if (class_exists(\PDO::class)) {
  72. return \PDO::getAvailableDrivers();
  73. }
  74. return [];
  75. }
  76. /**
  77. * Get the available and supported databases of this instance
  78. *
  79. * @return array
  80. * @throws Exception
  81. */
  82. public function getSupportedDatabases(bool $allowAllDatabases = false): array {
  83. $availableDatabases = [
  84. 'sqlite' => [
  85. 'type' => 'pdo',
  86. 'call' => 'sqlite',
  87. 'name' => 'SQLite',
  88. ],
  89. 'mysql' => [
  90. 'type' => 'pdo',
  91. 'call' => 'mysql',
  92. 'name' => 'MySQL/MariaDB',
  93. ],
  94. 'pgsql' => [
  95. 'type' => 'pdo',
  96. 'call' => 'pgsql',
  97. 'name' => 'PostgreSQL',
  98. ],
  99. 'oci' => [
  100. 'type' => 'function',
  101. 'call' => 'oci_connect',
  102. 'name' => 'Oracle',
  103. ],
  104. ];
  105. if ($allowAllDatabases) {
  106. $configuredDatabases = array_keys($availableDatabases);
  107. } else {
  108. $configuredDatabases = $this->config->getValue('supportedDatabases',
  109. ['sqlite', 'mysql', 'pgsql']);
  110. }
  111. if (!is_array($configuredDatabases)) {
  112. throw new Exception('Supported databases are not properly configured.');
  113. }
  114. $supportedDatabases = [];
  115. foreach ($configuredDatabases as $database) {
  116. if (array_key_exists($database, $availableDatabases)) {
  117. $working = false;
  118. $type = $availableDatabases[$database]['type'];
  119. $call = $availableDatabases[$database]['call'];
  120. if ($type === 'function') {
  121. $working = $this->is_callable($call);
  122. } elseif ($type === 'pdo') {
  123. $working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
  124. }
  125. if ($working) {
  126. $supportedDatabases[$database] = $availableDatabases[$database]['name'];
  127. }
  128. }
  129. }
  130. return $supportedDatabases;
  131. }
  132. /**
  133. * Gathers system information like database type and does
  134. * a few system checks.
  135. *
  136. * @return array of system info, including an "errors" value
  137. * in case of errors/warnings
  138. */
  139. public function getSystemInfo(bool $allowAllDatabases = false): array {
  140. $databases = $this->getSupportedDatabases($allowAllDatabases);
  141. $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
  142. $errors = [];
  143. // Create data directory to test whether the .htaccess works
  144. // Notice that this is not necessarily the same data directory as the one
  145. // that will effectively be used.
  146. if (!file_exists($dataDir)) {
  147. @mkdir($dataDir);
  148. }
  149. $htAccessWorking = true;
  150. if (is_dir($dataDir) && is_writable($dataDir)) {
  151. // Protect data directory here, so we can test if the protection is working
  152. self::protectDataDirectory();
  153. try {
  154. $util = new \OC_Util();
  155. $htAccessWorking = $util->isHtaccessWorking(Server::get(IConfig::class));
  156. } catch (\OCP\HintException $e) {
  157. $errors[] = [
  158. 'error' => $e->getMessage(),
  159. 'exception' => $e,
  160. 'hint' => $e->getHint(),
  161. ];
  162. $htAccessWorking = false;
  163. }
  164. }
  165. if (\OC_Util::runningOnMac()) {
  166. $errors[] = [
  167. 'error' => $this->l10n->t(
  168. 'Mac OS X is not supported and %s will not work properly on this platform. ' .
  169. 'Use it at your own risk! ',
  170. [$this->defaults->getProductName()]
  171. ),
  172. 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
  173. ];
  174. }
  175. if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
  176. $errors[] = [
  177. 'error' => $this->l10n->t(
  178. 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
  179. 'This will lead to problems with files over 4 GB and is highly discouraged.',
  180. [$this->defaults->getProductName()]
  181. ),
  182. 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
  183. ];
  184. }
  185. return [
  186. 'hasSQLite' => isset($databases['sqlite']),
  187. 'hasMySQL' => isset($databases['mysql']),
  188. 'hasPostgreSQL' => isset($databases['pgsql']),
  189. 'hasOracle' => isset($databases['oci']),
  190. 'databases' => $databases,
  191. 'directory' => $dataDir,
  192. 'htaccessWorking' => $htAccessWorking,
  193. 'errors' => $errors,
  194. ];
  195. }
  196. /**
  197. * @return array<string|array> errors
  198. */
  199. public function install(array $options, ?IOutput $output = null): array {
  200. $l = $this->l10n;
  201. $error = [];
  202. $dbType = $options['dbtype'];
  203. if (empty($options['adminlogin'])) {
  204. $error[] = $l->t('Set an admin Login.');
  205. }
  206. if (empty($options['adminpass'])) {
  207. $error[] = $l->t('Set an admin password.');
  208. }
  209. if (empty($options['directory'])) {
  210. $options['directory'] = \OC::$SERVERROOT . '/data';
  211. }
  212. if (!isset(self::$dbSetupClasses[$dbType])) {
  213. $dbType = 'sqlite';
  214. }
  215. $username = htmlspecialchars_decode($options['adminlogin']);
  216. $password = htmlspecialchars_decode($options['adminpass']);
  217. $dataDir = htmlspecialchars_decode($options['directory']);
  218. $class = self::$dbSetupClasses[$dbType];
  219. /** @var \OC\Setup\AbstractDatabase $dbSetup */
  220. $dbSetup = new $class($l, $this->config, $this->logger, $this->random);
  221. $error = array_merge($error, $dbSetup->validate($options));
  222. // validate the data directory
  223. if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
  224. $error[] = $l->t('Cannot create or write into the data directory %s', [$dataDir]);
  225. }
  226. if (!empty($error)) {
  227. return $error;
  228. }
  229. $request = Server::get(IRequest::class);
  230. //no errors, good
  231. if (isset($options['trusted_domains'])
  232. && is_array($options['trusted_domains'])) {
  233. $trustedDomains = $options['trusted_domains'];
  234. } else {
  235. $trustedDomains = [$request->getInsecureServerHost()];
  236. }
  237. //use sqlite3 when available, otherwise sqlite2 will be used.
  238. if ($dbType === 'sqlite' && class_exists('SQLite3')) {
  239. $dbType = 'sqlite3';
  240. }
  241. //generate a random salt that is used to salt the local passwords
  242. $salt = $this->random->generate(30);
  243. // generate a secret
  244. $secret = $this->random->generate(48);
  245. //write the config file
  246. $newConfigValues = [
  247. 'passwordsalt' => $salt,
  248. 'secret' => $secret,
  249. 'trusted_domains' => $trustedDomains,
  250. 'datadirectory' => $dataDir,
  251. 'dbtype' => $dbType,
  252. 'version' => implode('.', \OCP\Util::getVersion()),
  253. ];
  254. if ($this->config->getValue('overwrite.cli.url', null) === null) {
  255. $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
  256. }
  257. $this->config->setValues($newConfigValues);
  258. $this->outputDebug($output, 'Configuring database');
  259. $dbSetup->initialize($options);
  260. try {
  261. $dbSetup->setupDatabase($username);
  262. } catch (\OC\DatabaseSetupException $e) {
  263. $error[] = [
  264. 'error' => $e->getMessage(),
  265. 'exception' => $e,
  266. 'hint' => $e->getHint(),
  267. ];
  268. return $error;
  269. } catch (Exception $e) {
  270. $error[] = [
  271. 'error' => 'Error while trying to create admin account: ' . $e->getMessage(),
  272. 'exception' => $e,
  273. 'hint' => '',
  274. ];
  275. return $error;
  276. }
  277. $this->outputDebug($output, 'Run server migrations');
  278. try {
  279. // apply necessary migrations
  280. $dbSetup->runMigrations($output);
  281. } catch (Exception $e) {
  282. $error[] = [
  283. 'error' => 'Error while trying to initialise the database: ' . $e->getMessage(),
  284. 'exception' => $e,
  285. 'hint' => '',
  286. ];
  287. return $error;
  288. }
  289. $this->outputDebug($output, 'Create admin account');
  290. // create the admin account and group
  291. $user = null;
  292. try {
  293. $user = Server::get(IUserManager::class)->createUser($username, $password);
  294. if (!$user) {
  295. $error[] = "Account <$username> could not be created.";
  296. return $error;
  297. }
  298. } catch (Exception $exception) {
  299. $error[] = $exception->getMessage();
  300. return $error;
  301. }
  302. $config = Server::get(IConfig::class);
  303. $config->setAppValue('core', 'installedat', (string)microtime(true));
  304. $appConfig = Server::get(IAppConfig::class);
  305. $appConfig->setValueInt('core', 'lastupdatedat', time());
  306. $vendorData = $this->getVendorData();
  307. $config->setAppValue('core', 'vendor', $vendorData['vendor']);
  308. if ($vendorData['channel'] !== 'stable') {
  309. $config->setSystemValue('updater.release.channel', $vendorData['channel']);
  310. }
  311. $group = Server::get(IGroupManager::class)->createGroup('admin');
  312. if ($group instanceof IGroup) {
  313. $group->addUser($user);
  314. }
  315. // Install shipped apps and specified app bundles
  316. $this->outputDebug($output, 'Install default apps');
  317. Installer::installShippedApps(false, $output);
  318. // create empty file in data dir, so we can later find
  319. // out that this is indeed a Nextcloud data directory
  320. $this->outputDebug($output, 'Setup data directory');
  321. file_put_contents(
  322. $config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/.ncdata',
  323. "# Nextcloud data directory\n# Do not change this file",
  324. );
  325. // Update .htaccess files
  326. self::updateHtaccess();
  327. self::protectDataDirectory();
  328. $this->outputDebug($output, 'Install background jobs');
  329. self::installBackgroundJobs();
  330. //and we are done
  331. $config->setSystemValue('installed', true);
  332. if (self::shouldRemoveCanInstallFile()) {
  333. unlink(\OC::$configDir . '/CAN_INSTALL');
  334. }
  335. $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
  336. $bootstrapCoordinator->runInitialRegistration();
  337. // Create a session token for the newly created user
  338. // The token provider requires a working db, so it's not injected on setup
  339. /** @var \OC\User\Session $userSession */
  340. $userSession = Server::get(IUserSession::class);
  341. $provider = Server::get(PublicKeyTokenProvider::class);
  342. $userSession->setTokenProvider($provider);
  343. $userSession->login($username, $password);
  344. $user = $userSession->getUser();
  345. if (!$user) {
  346. $error[] = 'No account found in session.';
  347. return $error;
  348. }
  349. $userSession->createSessionToken($request, $user->getUID(), $username, $password);
  350. $session = $userSession->getSession();
  351. $session->set('last-password-confirm', Server::get(ITimeFactory::class)->getTime());
  352. // Set email for admin
  353. if (!empty($options['adminemail'])) {
  354. $user->setSystemEMailAddress($options['adminemail']);
  355. }
  356. return $error;
  357. }
  358. public static function installBackgroundJobs(): void {
  359. $jobList = Server::get(IJobList::class);
  360. $jobList->add(TokenCleanupJob::class);
  361. $jobList->add(Rotate::class);
  362. $jobList->add(BackgroundCleanupJob::class);
  363. $jobList->add(RemoveOldTasksBackgroundJob::class);
  364. $jobList->add(CleanupDeletedUsers::class);
  365. }
  366. /**
  367. * @return string Absolute path to htaccess
  368. */
  369. private function pathToHtaccess(): string {
  370. return \OC::$SERVERROOT . '/.htaccess';
  371. }
  372. /**
  373. * Find webroot from config
  374. *
  375. * @throws InvalidArgumentException when invalid value for overwrite.cli.url
  376. */
  377. private static function findWebRoot(SystemConfig $config): string {
  378. // For CLI read the value from overwrite.cli.url
  379. if (\OC::$CLI) {
  380. $webRoot = $config->getValue('overwrite.cli.url', '');
  381. if ($webRoot === '') {
  382. throw new InvalidArgumentException('overwrite.cli.url is empty');
  383. }
  384. if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
  385. throw new InvalidArgumentException('invalid value for overwrite.cli.url');
  386. }
  387. $webRoot = rtrim((parse_url($webRoot, PHP_URL_PATH) ?? ''), '/');
  388. } else {
  389. $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
  390. }
  391. return $webRoot;
  392. }
  393. /**
  394. * Append the correct ErrorDocument path for Apache hosts
  395. *
  396. * @return bool True when success, False otherwise
  397. * @throws \OCP\AppFramework\QueryException
  398. */
  399. public static function updateHtaccess(): bool {
  400. $config = Server::get(SystemConfig::class);
  401. try {
  402. $webRoot = self::findWebRoot($config);
  403. } catch (InvalidArgumentException $e) {
  404. return false;
  405. }
  406. $setupHelper = Server::get(\OC\Setup::class);
  407. if (!is_writable($setupHelper->pathToHtaccess())) {
  408. return false;
  409. }
  410. $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
  411. $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
  412. $htaccessContent = explode($content, $htaccessContent, 2)[0];
  413. //custom 403 error page
  414. $content .= "\nErrorDocument 403 " . $webRoot . '/index.php/error/403';
  415. //custom 404 error page
  416. $content .= "\nErrorDocument 404 " . $webRoot . '/index.php/error/404';
  417. // Add rewrite rules if the RewriteBase is configured
  418. $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
  419. if ($rewriteBase !== '') {
  420. $content .= "\n<IfModule mod_rewrite.c>";
  421. $content .= "\n Options -MultiViews";
  422. $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
  423. $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
  424. $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|mjs|svg|gif|ico|jpg|jpeg|png|webp|html|otf|ttf|woff2?|map|webm|mp4|mp3|ogg|wav|flac|wasm|tflite)$";
  425. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php";
  426. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$";
  427. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php";
  428. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php";
  429. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots\\.txt";
  430. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(ocs-provider|updater)/";
  431. $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
  432. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$";
  433. $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]";
  434. $content .= "\n RewriteBase " . $rewriteBase;
  435. $content .= "\n <IfModule mod_env.c>";
  436. $content .= "\n SetEnv front_controller_active true";
  437. $content .= "\n <IfModule mod_dir.c>";
  438. $content .= "\n DirectorySlash off";
  439. $content .= "\n </IfModule>";
  440. $content .= "\n </IfModule>";
  441. $content .= "\n</IfModule>";
  442. }
  443. // Never write file back if disk space should be too low
  444. if (function_exists('disk_free_space')) {
  445. $df = disk_free_space(\OC::$SERVERROOT);
  446. $size = strlen($content) + 10240;
  447. if ($df !== false && $df < (float)$size) {
  448. throw new \Exception(\OC::$SERVERROOT . ' does not have enough space for writing the htaccess file! Not writing it back!');
  449. }
  450. }
  451. //suppress errors in case we don't have permissions for it
  452. return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
  453. }
  454. public static function protectDataDirectory(): void {
  455. //Require all denied
  456. $now = date('Y-m-d H:i:s');
  457. $content = "# Generated by Nextcloud on $now\n";
  458. $content .= "# Section for Apache 2.4 to 2.6\n";
  459. $content .= "<IfModule mod_authz_core.c>\n";
  460. $content .= " Require all denied\n";
  461. $content .= "</IfModule>\n";
  462. $content .= "<IfModule mod_access_compat.c>\n";
  463. $content .= " Order Allow,Deny\n";
  464. $content .= " Deny from all\n";
  465. $content .= " Satisfy All\n";
  466. $content .= "</IfModule>\n\n";
  467. $content .= "# Section for Apache 2.2\n";
  468. $content .= "<IfModule !mod_authz_core.c>\n";
  469. $content .= " <IfModule !mod_access_compat.c>\n";
  470. $content .= " <IfModule mod_authz_host.c>\n";
  471. $content .= " Order Allow,Deny\n";
  472. $content .= " Deny from all\n";
  473. $content .= " </IfModule>\n";
  474. $content .= " Satisfy All\n";
  475. $content .= " </IfModule>\n";
  476. $content .= "</IfModule>\n\n";
  477. $content .= "# Section for Apache 2.2 to 2.6\n";
  478. $content .= "<IfModule mod_autoindex.c>\n";
  479. $content .= " IndexIgnore *\n";
  480. $content .= '</IfModule>';
  481. $baseDir = Server::get(IConfig::class)->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  482. file_put_contents($baseDir . '/.htaccess', $content);
  483. file_put_contents($baseDir . '/index.html', '');
  484. }
  485. private function getVendorData(): array {
  486. // this should really be a JSON file
  487. require \OC::$SERVERROOT . '/version.php';
  488. /** @var mixed $vendor */
  489. /** @var mixed $OC_Channel */
  490. return [
  491. 'vendor' => (string)$vendor,
  492. 'channel' => (string)$OC_Channel,
  493. ];
  494. }
  495. public function shouldRemoveCanInstallFile(): bool {
  496. return Server::get(ServerVersion::class)->getChannel() !== 'git' && is_file(\OC::$configDir . '/CAN_INSTALL');
  497. }
  498. public function canInstallFileExists(): bool {
  499. return is_file(\OC::$configDir . '/CAN_INSTALL');
  500. }
  501. protected function outputDebug(?IOutput $output, string $message): void {
  502. if ($output instanceof IOutput) {
  503. $output->debug($message);
  504. }
  505. }
  506. }