1
0

Setup.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 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 = \OCP\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. $jobList->add(CleanupDeletedUsers::class);
  364. }
  365. /**
  366. * @return string Absolute path to htaccess
  367. */
  368. private function pathToHtaccess(): string {
  369. return \OC::$SERVERROOT . '/.htaccess';
  370. }
  371. /**
  372. * Find webroot from config
  373. *
  374. * @throws InvalidArgumentException when invalid value for overwrite.cli.url
  375. */
  376. private static function findWebRoot(SystemConfig $config): string {
  377. // For CLI read the value from overwrite.cli.url
  378. if (\OC::$CLI) {
  379. $webRoot = $config->getValue('overwrite.cli.url', '');
  380. if ($webRoot === '') {
  381. throw new InvalidArgumentException('overwrite.cli.url is empty');
  382. }
  383. if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
  384. throw new InvalidArgumentException('invalid value for overwrite.cli.url');
  385. }
  386. $webRoot = rtrim((parse_url($webRoot, PHP_URL_PATH) ?? ''), '/');
  387. } else {
  388. $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
  389. }
  390. return $webRoot;
  391. }
  392. /**
  393. * Append the correct ErrorDocument path for Apache hosts
  394. *
  395. * @return bool True when success, False otherwise
  396. * @throws \OCP\AppFramework\QueryException
  397. */
  398. public static function updateHtaccess(): bool {
  399. $config = Server::get(SystemConfig::class);
  400. try {
  401. $webRoot = self::findWebRoot($config);
  402. } catch (InvalidArgumentException $e) {
  403. return false;
  404. }
  405. $setupHelper = Server::get(\OC\Setup::class);
  406. if (!is_writable($setupHelper->pathToHtaccess())) {
  407. return false;
  408. }
  409. $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
  410. $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
  411. $htaccessContent = explode($content, $htaccessContent, 2)[0];
  412. //custom 403 error page
  413. $content .= "\nErrorDocument 403 " . $webRoot . '/index.php/error/403';
  414. //custom 404 error page
  415. $content .= "\nErrorDocument 404 " . $webRoot . '/index.php/error/404';
  416. // Add rewrite rules if the RewriteBase is configured
  417. $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
  418. if ($rewriteBase !== '') {
  419. $content .= "\n<IfModule mod_rewrite.c>";
  420. $content .= "\n Options -MultiViews";
  421. $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
  422. $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
  423. $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)$";
  424. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php";
  425. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$";
  426. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php";
  427. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php";
  428. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots\\.txt";
  429. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(ocs-provider|updater)/";
  430. $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
  431. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$";
  432. $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]";
  433. $content .= "\n RewriteBase " . $rewriteBase;
  434. $content .= "\n <IfModule mod_env.c>";
  435. $content .= "\n SetEnv front_controller_active true";
  436. $content .= "\n <IfModule mod_dir.c>";
  437. $content .= "\n DirectorySlash off";
  438. $content .= "\n </IfModule>";
  439. $content .= "\n </IfModule>";
  440. $content .= "\n</IfModule>";
  441. }
  442. // Never write file back if disk space should be too low
  443. if (function_exists('disk_free_space')) {
  444. $df = disk_free_space(\OC::$SERVERROOT);
  445. $size = strlen($content) + 10240;
  446. if ($df !== false && $df < (float)$size) {
  447. throw new \Exception(\OC::$SERVERROOT . " does not have enough space for writing the htaccess file! Not writing it back!");
  448. }
  449. }
  450. //suppress errors in case we don't have permissions for it
  451. return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
  452. }
  453. public static function protectDataDirectory(): void {
  454. //Require all denied
  455. $now = date('Y-m-d H:i:s');
  456. $content = "# Generated by Nextcloud on $now\n";
  457. $content .= "# Section for Apache 2.4 to 2.6\n";
  458. $content .= "<IfModule mod_authz_core.c>\n";
  459. $content .= " Require all denied\n";
  460. $content .= "</IfModule>\n";
  461. $content .= "<IfModule mod_access_compat.c>\n";
  462. $content .= " Order Allow,Deny\n";
  463. $content .= " Deny from all\n";
  464. $content .= " Satisfy All\n";
  465. $content .= "</IfModule>\n\n";
  466. $content .= "# Section for Apache 2.2\n";
  467. $content .= "<IfModule !mod_authz_core.c>\n";
  468. $content .= " <IfModule !mod_access_compat.c>\n";
  469. $content .= " <IfModule mod_authz_host.c>\n";
  470. $content .= " Order Allow,Deny\n";
  471. $content .= " Deny from all\n";
  472. $content .= " </IfModule>\n";
  473. $content .= " Satisfy All\n";
  474. $content .= " </IfModule>\n";
  475. $content .= "</IfModule>\n\n";
  476. $content .= "# Section for Apache 2.2 to 2.6\n";
  477. $content .= "<IfModule mod_autoindex.c>\n";
  478. $content .= " IndexIgnore *\n";
  479. $content .= "</IfModule>";
  480. $baseDir = Server::get(IConfig::class)->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  481. file_put_contents($baseDir . '/.htaccess', $content);
  482. file_put_contents($baseDir . '/index.html', '');
  483. }
  484. private function getVendorData(): array {
  485. // this should really be a JSON file
  486. require \OC::$SERVERROOT . '/version.php';
  487. /** @var mixed $vendor */
  488. /** @var mixed $OC_Channel */
  489. return [
  490. 'vendor' => (string)$vendor,
  491. 'channel' => (string)$OC_Channel,
  492. ];
  493. }
  494. public function shouldRemoveCanInstallFile(): bool {
  495. return \OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL');
  496. }
  497. public function canInstallFileExists(): bool {
  498. return is_file(\OC::$configDir.'/CAN_INSTALL');
  499. }
  500. protected function outputDebug(?IOutput $output, string $message): void {
  501. if ($output instanceof IOutput) {
  502. $output->debug($message);
  503. }
  504. }
  505. }