Setup.php 18 KB

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