Setup.php 18 KB

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