1
0

Setup.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 an ownCloud data directory
  318. $this->outputDebug($output, 'Setup data directory');
  319. file_put_contents($config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
  320. // Update .htaccess files
  321. self::updateHtaccess();
  322. self::protectDataDirectory();
  323. $this->outputDebug($output, 'Install background jobs');
  324. self::installBackgroundJobs();
  325. //and we are done
  326. $config->setSystemValue('installed', true);
  327. if (self::shouldRemoveCanInstallFile()) {
  328. unlink(\OC::$configDir.'/CAN_INSTALL');
  329. }
  330. $bootstrapCoordinator = \OCP\Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
  331. $bootstrapCoordinator->runInitialRegistration();
  332. // Create a session token for the newly created user
  333. // The token provider requires a working db, so it's not injected on setup
  334. /** @var \OC\User\Session $userSession */
  335. $userSession = Server::get(IUserSession::class);
  336. $provider = Server::get(PublicKeyTokenProvider::class);
  337. $userSession->setTokenProvider($provider);
  338. $userSession->login($username, $password);
  339. $user = $userSession->getUser();
  340. if (!$user) {
  341. $error[] = "No account found in session.";
  342. return $error;
  343. }
  344. $userSession->createSessionToken($request, $user->getUID(), $username, $password);
  345. $session = $userSession->getSession();
  346. $session->set('last-password-confirm', Server::get(ITimeFactory::class)->getTime());
  347. // Set email for admin
  348. if (!empty($options['adminemail'])) {
  349. $user->setSystemEMailAddress($options['adminemail']);
  350. }
  351. return $error;
  352. }
  353. public static function installBackgroundJobs(): void {
  354. $jobList = Server::get(IJobList::class);
  355. $jobList->add(TokenCleanupJob::class);
  356. $jobList->add(Rotate::class);
  357. $jobList->add(BackgroundCleanupJob::class);
  358. $jobList->add(RemoveOldTasksBackgroundJob::class);
  359. }
  360. /**
  361. * @return string Absolute path to htaccess
  362. */
  363. private function pathToHtaccess(): string {
  364. return \OC::$SERVERROOT . '/.htaccess';
  365. }
  366. /**
  367. * Find webroot from config
  368. *
  369. * @throws InvalidArgumentException when invalid value for overwrite.cli.url
  370. */
  371. private static function findWebRoot(SystemConfig $config): string {
  372. // For CLI read the value from overwrite.cli.url
  373. if (\OC::$CLI) {
  374. $webRoot = $config->getValue('overwrite.cli.url', '');
  375. if ($webRoot === '') {
  376. throw new InvalidArgumentException('overwrite.cli.url is empty');
  377. }
  378. if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
  379. throw new InvalidArgumentException('invalid value for overwrite.cli.url');
  380. }
  381. $webRoot = rtrim((parse_url($webRoot, PHP_URL_PATH) ?? ''), '/');
  382. } else {
  383. $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
  384. }
  385. return $webRoot;
  386. }
  387. /**
  388. * Append the correct ErrorDocument path for Apache hosts
  389. *
  390. * @return bool True when success, False otherwise
  391. * @throws \OCP\AppFramework\QueryException
  392. */
  393. public static function updateHtaccess(): bool {
  394. $config = Server::get(SystemConfig::class);
  395. try {
  396. $webRoot = self::findWebRoot($config);
  397. } catch (InvalidArgumentException $e) {
  398. return false;
  399. }
  400. $setupHelper = Server::get(\OC\Setup::class);
  401. if (!is_writable($setupHelper->pathToHtaccess())) {
  402. return false;
  403. }
  404. $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
  405. $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
  406. $htaccessContent = explode($content, $htaccessContent, 2)[0];
  407. //custom 403 error page
  408. $content .= "\nErrorDocument 403 " . $webRoot . '/index.php/error/403';
  409. //custom 404 error page
  410. $content .= "\nErrorDocument 404 " . $webRoot . '/index.php/error/404';
  411. // Add rewrite rules if the RewriteBase is configured
  412. $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
  413. if ($rewriteBase !== '') {
  414. $content .= "\n<IfModule mod_rewrite.c>";
  415. $content .= "\n Options -MultiViews";
  416. $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
  417. $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
  418. $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|mjs|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav|flac|wasm|tflite)$";
  419. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php";
  420. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$";
  421. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php";
  422. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php";
  423. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots\\.txt";
  424. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(ocs-provider|updater)/";
  425. $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
  426. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$";
  427. $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]";
  428. $content .= "\n RewriteBase " . $rewriteBase;
  429. $content .= "\n <IfModule mod_env.c>";
  430. $content .= "\n SetEnv front_controller_active true";
  431. $content .= "\n <IfModule mod_dir.c>";
  432. $content .= "\n DirectorySlash off";
  433. $content .= "\n </IfModule>";
  434. $content .= "\n </IfModule>";
  435. $content .= "\n</IfModule>";
  436. }
  437. // Never write file back if disk space should be too low
  438. if (function_exists('disk_free_space')) {
  439. $df = disk_free_space(\OC::$SERVERROOT);
  440. $size = strlen($content) + 10240;
  441. if ($df !== false && $df < (float)$size) {
  442. throw new \Exception(\OC::$SERVERROOT . " does not have enough space for writing the htaccess file! Not writing it back!");
  443. }
  444. }
  445. //suppress errors in case we don't have permissions for it
  446. return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
  447. }
  448. public static function protectDataDirectory(): void {
  449. //Require all denied
  450. $now = date('Y-m-d H:i:s');
  451. $content = "# Generated by Nextcloud on $now\n";
  452. $content .= "# Section for Apache 2.4 to 2.6\n";
  453. $content .= "<IfModule mod_authz_core.c>\n";
  454. $content .= " Require all denied\n";
  455. $content .= "</IfModule>\n";
  456. $content .= "<IfModule mod_access_compat.c>\n";
  457. $content .= " Order Allow,Deny\n";
  458. $content .= " Deny from all\n";
  459. $content .= " Satisfy All\n";
  460. $content .= "</IfModule>\n\n";
  461. $content .= "# Section for Apache 2.2\n";
  462. $content .= "<IfModule !mod_authz_core.c>\n";
  463. $content .= " <IfModule !mod_access_compat.c>\n";
  464. $content .= " <IfModule mod_authz_host.c>\n";
  465. $content .= " Order Allow,Deny\n";
  466. $content .= " Deny from all\n";
  467. $content .= " </IfModule>\n";
  468. $content .= " Satisfy All\n";
  469. $content .= " </IfModule>\n";
  470. $content .= "</IfModule>\n\n";
  471. $content .= "# Section for Apache 2.2 to 2.6\n";
  472. $content .= "<IfModule mod_autoindex.c>\n";
  473. $content .= " IndexIgnore *\n";
  474. $content .= "</IfModule>";
  475. $baseDir = Server::get(IConfig::class)->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  476. file_put_contents($baseDir . '/.htaccess', $content);
  477. file_put_contents($baseDir . '/index.html', '');
  478. }
  479. private function getVendorData(): array {
  480. // this should really be a JSON file
  481. require \OC::$SERVERROOT . '/version.php';
  482. /** @var mixed $vendor */
  483. /** @var mixed $OC_Channel */
  484. return [
  485. 'vendor' => (string)$vendor,
  486. 'channel' => (string)$OC_Channel,
  487. ];
  488. }
  489. public function shouldRemoveCanInstallFile(): bool {
  490. return \OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL');
  491. }
  492. public function canInstallFileExists(): bool {
  493. return is_file(\OC::$configDir.'/CAN_INSTALL');
  494. }
  495. protected function outputDebug(?IOutput $output, string $message): void {
  496. if ($output instanceof IOutput) {
  497. $output->debug($message);
  498. }
  499. }
  500. }