You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

613 lines
19 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Administrator "Administrator@WINDOWS-2012"
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  9. * @author Bjoern Schiessle <bjoern@schiessle.org>
  10. * @author Brice Maron <brice@bmaron.net>
  11. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  12. * @author Dan Callahan <dan.callahan@gmail.com>
  13. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  14. * @author François Kubler <francois@kubler.org>
  15. * @author Frank Isemann <frank@isemann.name>
  16. * @author Jakob Sack <mail@jakobsack.de>
  17. * @author Joas Schilling <coding@schilljs.com>
  18. * @author Julius Härtl <jus@bitgrid.net>
  19. * @author KB7777 <k.burkowski@gmail.com>
  20. * @author Kevin Lanni <therealklanni@gmail.com>
  21. * @author Lukas Reschke <lukas@statuscode.ch>
  22. * @author MichaIng <28480705+MichaIng@users.noreply.github.com>
  23. * @author MichaIng <micha@dietpi.com>
  24. * @author Morris Jobke <hey@morrisjobke.de>
  25. * @author Robin Appelman <robin@icewind.nl>
  26. * @author Roeland Jago Douma <roeland@famdouma.nl>
  27. * @author Sean Comeau <sean@ftlnetworks.ca>
  28. * @author Serge Martin <edb@sigluy.net>
  29. * @author Simounet <contact@simounet.net>
  30. * @author Thomas Müller <thomas.mueller@tmit.eu>
  31. * @author Vincent Petry <pvince81@owncloud.com>
  32. *
  33. * @license AGPL-3.0
  34. *
  35. * This code is free software: you can redistribute it and/or modify
  36. * it under the terms of the GNU Affero General Public License, version 3,
  37. * as published by the Free Software Foundation.
  38. *
  39. * This program is distributed in the hope that it will be useful,
  40. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  41. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  42. * GNU Affero General Public License for more details.
  43. *
  44. * You should have received a copy of the GNU Affero General Public License, version 3,
  45. * along with this program. If not, see <http://www.gnu.org/licenses/>
  46. *
  47. */
  48. namespace OC;
  49. use bantu\IniGetWrapper\IniGetWrapper;
  50. use Exception;
  51. use InvalidArgumentException;
  52. use OC\App\AppStore\Bundles\BundleFetcher;
  53. use OC\Authentication\Token\DefaultTokenCleanupJob;
  54. use OC\Authentication\Token\DefaultTokenProvider;
  55. use OC\Log\Rotate;
  56. use OC\Preview\BackgroundCleanupJob;
  57. use OCP\AppFramework\Utility\ITimeFactory;
  58. use OCP\Defaults;
  59. use OCP\IGroup;
  60. use OCP\IL10N;
  61. use OCP\ILogger;
  62. use OCP\Security\ISecureRandom;
  63. class Setup {
  64. /** @var SystemConfig */
  65. protected $config;
  66. /** @var IniGetWrapper */
  67. protected $iniWrapper;
  68. /** @var IL10N */
  69. protected $l10n;
  70. /** @var Defaults */
  71. protected $defaults;
  72. /** @var ILogger */
  73. protected $logger;
  74. /** @var ISecureRandom */
  75. protected $random;
  76. /** @var Installer */
  77. protected $installer;
  78. /**
  79. * @param SystemConfig $config
  80. * @param IniGetWrapper $iniWrapper
  81. * @param IL10N $l10n
  82. * @param Defaults $defaults
  83. * @param ILogger $logger
  84. * @param ISecureRandom $random
  85. * @param Installer $installer
  86. */
  87. public function __construct(
  88. SystemConfig $config,
  89. IniGetWrapper $iniWrapper,
  90. IL10N $l10n,
  91. Defaults $defaults,
  92. ILogger $logger,
  93. ISecureRandom $random,
  94. Installer $installer
  95. ) {
  96. $this->config = $config;
  97. $this->iniWrapper = $iniWrapper;
  98. $this->l10n = $l10n;
  99. $this->defaults = $defaults;
  100. $this->logger = $logger;
  101. $this->random = $random;
  102. $this->installer = $installer;
  103. }
  104. protected static $dbSetupClasses = [
  105. 'mysql' => \OC\Setup\MySQL::class,
  106. 'pgsql' => \OC\Setup\PostgreSQL::class,
  107. 'oci' => \OC\Setup\OCI::class,
  108. 'sqlite' => \OC\Setup\Sqlite::class,
  109. 'sqlite3' => \OC\Setup\Sqlite::class,
  110. ];
  111. /**
  112. * Wrapper around the "class_exists" PHP function to be able to mock it
  113. *
  114. * @param string $name
  115. * @return bool
  116. */
  117. protected function class_exists($name) {
  118. return class_exists($name);
  119. }
  120. /**
  121. * Wrapper around the "is_callable" PHP function to be able to mock it
  122. *
  123. * @param string $name
  124. * @return bool
  125. */
  126. protected function is_callable($name) {
  127. return is_callable($name);
  128. }
  129. /**
  130. * Wrapper around \PDO::getAvailableDrivers
  131. *
  132. * @return array
  133. */
  134. protected function getAvailableDbDriversForPdo() {
  135. return \PDO::getAvailableDrivers();
  136. }
  137. /**
  138. * Get the available and supported databases of this instance
  139. *
  140. * @param bool $allowAllDatabases
  141. * @return array
  142. * @throws Exception
  143. */
  144. public function getSupportedDatabases($allowAllDatabases = false) {
  145. $availableDatabases = [
  146. 'sqlite' => [
  147. 'type' => 'pdo',
  148. 'call' => 'sqlite',
  149. 'name' => 'SQLite',
  150. ],
  151. 'mysql' => [
  152. 'type' => 'pdo',
  153. 'call' => 'mysql',
  154. 'name' => 'MySQL/MariaDB',
  155. ],
  156. 'pgsql' => [
  157. 'type' => 'pdo',
  158. 'call' => 'pgsql',
  159. 'name' => 'PostgreSQL',
  160. ],
  161. 'oci' => [
  162. 'type' => 'function',
  163. 'call' => 'oci_connect',
  164. 'name' => 'Oracle',
  165. ],
  166. ];
  167. if ($allowAllDatabases) {
  168. $configuredDatabases = array_keys($availableDatabases);
  169. } else {
  170. $configuredDatabases = $this->config->getValue('supportedDatabases',
  171. ['sqlite', 'mysql', 'pgsql']);
  172. }
  173. if (!is_array($configuredDatabases)) {
  174. throw new Exception('Supported databases are not properly configured.');
  175. }
  176. $supportedDatabases = [];
  177. foreach ($configuredDatabases as $database) {
  178. if (array_key_exists($database, $availableDatabases)) {
  179. $working = false;
  180. $type = $availableDatabases[$database]['type'];
  181. $call = $availableDatabases[$database]['call'];
  182. if ($type === 'function') {
  183. $working = $this->is_callable($call);
  184. } elseif ($type === 'pdo') {
  185. $working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
  186. }
  187. if ($working) {
  188. $supportedDatabases[$database] = $availableDatabases[$database]['name'];
  189. }
  190. }
  191. }
  192. return $supportedDatabases;
  193. }
  194. /**
  195. * Gathers system information like database type and does
  196. * a few system checks.
  197. *
  198. * @return array of system info, including an "errors" value
  199. * in case of errors/warnings
  200. */
  201. public function getSystemInfo($allowAllDatabases = false) {
  202. $databases = $this->getSupportedDatabases($allowAllDatabases);
  203. $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
  204. $errors = [];
  205. // Create data directory to test whether the .htaccess works
  206. // Notice that this is not necessarily the same data directory as the one
  207. // that will effectively be used.
  208. if (!file_exists($dataDir)) {
  209. @mkdir($dataDir);
  210. }
  211. $htAccessWorking = true;
  212. if (is_dir($dataDir) && is_writable($dataDir)) {
  213. // Protect data directory here, so we can test if the protection is working
  214. self::protectDataDirectory();
  215. try {
  216. $util = new \OC_Util();
  217. $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
  218. } catch (\OC\HintException $e) {
  219. $errors[] = [
  220. 'error' => $e->getMessage(),
  221. 'hint' => $e->getHint(),
  222. ];
  223. $htAccessWorking = false;
  224. }
  225. }
  226. if (\OC_Util::runningOnMac()) {
  227. $errors[] = [
  228. 'error' => $this->l10n->t(
  229. 'Mac OS X is not supported and %s will not work properly on this platform. ' .
  230. 'Use it at your own risk! ',
  231. [$this->defaults->getName()]
  232. ),
  233. 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
  234. ];
  235. }
  236. if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
  237. $errors[] = [
  238. 'error' => $this->l10n->t(
  239. 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
  240. 'This will lead to problems with files over 4 GB and is highly discouraged.',
  241. [$this->defaults->getName()]
  242. ),
  243. 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
  244. ];
  245. }
  246. return [
  247. 'hasSQLite' => isset($databases['sqlite']),
  248. 'hasMySQL' => isset($databases['mysql']),
  249. 'hasPostgreSQL' => isset($databases['pgsql']),
  250. 'hasOracle' => isset($databases['oci']),
  251. 'databases' => $databases,
  252. 'directory' => $dataDir,
  253. 'htaccessWorking' => $htAccessWorking,
  254. 'errors' => $errors,
  255. ];
  256. }
  257. /**
  258. * @param $options
  259. * @return array
  260. */
  261. public function install($options) {
  262. $l = $this->l10n;
  263. $error = [];
  264. $dbType = $options['dbtype'];
  265. if (empty($options['adminlogin'])) {
  266. $error[] = $l->t('Set an admin username.');
  267. }
  268. if (empty($options['adminpass'])) {
  269. $error[] = $l->t('Set an admin password.');
  270. }
  271. if (empty($options['directory'])) {
  272. $options['directory'] = \OC::$SERVERROOT . "/data";
  273. }
  274. if (!isset(self::$dbSetupClasses[$dbType])) {
  275. $dbType = 'sqlite';
  276. }
  277. $username = htmlspecialchars_decode($options['adminlogin']);
  278. $password = htmlspecialchars_decode($options['adminpass']);
  279. $dataDir = htmlspecialchars_decode($options['directory']);
  280. $class = self::$dbSetupClasses[$dbType];
  281. /** @var \OC\Setup\AbstractDatabase $dbSetup */
  282. $dbSetup = new $class($l, $this->config, $this->logger, $this->random);
  283. $error = array_merge($error, $dbSetup->validate($options));
  284. // validate the data directory
  285. if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
  286. $error[] = $l->t("Can't create or write into the data directory %s", [$dataDir]);
  287. }
  288. if (!empty($error)) {
  289. return $error;
  290. }
  291. $request = \OC::$server->getRequest();
  292. //no errors, good
  293. if (isset($options['trusted_domains'])
  294. && is_array($options['trusted_domains'])) {
  295. $trustedDomains = $options['trusted_domains'];
  296. } else {
  297. $trustedDomains = [$request->getInsecureServerHost()];
  298. }
  299. //use sqlite3 when available, otherwise sqlite2 will be used.
  300. if ($dbType === 'sqlite' && class_exists('SQLite3')) {
  301. $dbType = 'sqlite3';
  302. }
  303. //generate a random salt that is used to salt the local user passwords
  304. $salt = $this->random->generate(30);
  305. // generate a secret
  306. $secret = $this->random->generate(48);
  307. //write the config file
  308. $newConfigValues = [
  309. 'passwordsalt' => $salt,
  310. 'secret' => $secret,
  311. 'trusted_domains' => $trustedDomains,
  312. 'datadirectory' => $dataDir,
  313. 'dbtype' => $dbType,
  314. 'version' => implode('.', \OCP\Util::getVersion()),
  315. ];
  316. if ($this->config->getValue('overwrite.cli.url', null) === null) {
  317. $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
  318. }
  319. $this->config->setValues($newConfigValues);
  320. $dbSetup->initialize($options);
  321. try {
  322. $dbSetup->setupDatabase($username);
  323. } catch (\OC\DatabaseSetupException $e) {
  324. $error[] = [
  325. 'error' => $e->getMessage(),
  326. 'hint' => $e->getHint(),
  327. ];
  328. return $error;
  329. } catch (Exception $e) {
  330. $error[] = [
  331. 'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
  332. 'hint' => '',
  333. ];
  334. return $error;
  335. }
  336. try {
  337. // apply necessary migrations
  338. $dbSetup->runMigrations();
  339. } catch (Exception $e) {
  340. $error[] = [
  341. 'error' => 'Error while trying to initialise the database: ' . $e->getMessage(),
  342. 'hint' => '',
  343. ];
  344. return $error;
  345. }
  346. //create the user and group
  347. $user = null;
  348. try {
  349. $user = \OC::$server->getUserManager()->createUser($username, $password);
  350. if (!$user) {
  351. $error[] = "User <$username> could not be created.";
  352. }
  353. } catch (Exception $exception) {
  354. $error[] = $exception->getMessage();
  355. }
  356. if (empty($error)) {
  357. $config = \OC::$server->getConfig();
  358. $config->setAppValue('core', 'installedat', microtime(true));
  359. $config->setAppValue('core', 'lastupdatedat', microtime(true));
  360. $config->setAppValue('core', 'vendor', $this->getVendor());
  361. $group = \OC::$server->getGroupManager()->createGroup('admin');
  362. if ($group instanceof IGroup) {
  363. $group->addUser($user);
  364. }
  365. // Install shipped apps and specified app bundles
  366. Installer::installShippedApps();
  367. $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
  368. $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
  369. foreach ($defaultInstallationBundles as $bundle) {
  370. try {
  371. $this->installer->installAppBundle($bundle);
  372. } catch (Exception $e) {
  373. }
  374. }
  375. // create empty file in data dir, so we can later find
  376. // out that this is indeed an ownCloud data directory
  377. file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
  378. // Update .htaccess files
  379. self::updateHtaccess();
  380. self::protectDataDirectory();
  381. self::installBackgroundJobs();
  382. //and we are done
  383. $config->setSystemValue('installed', true);
  384. // Create a session token for the newly created user
  385. // The token provider requires a working db, so it's not injected on setup
  386. /* @var $userSession User\Session */
  387. $userSession = \OC::$server->getUserSession();
  388. $defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class);
  389. $userSession->setTokenProvider($defaultTokenProvider);
  390. $userSession->login($username, $password);
  391. $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
  392. $session = $userSession->getSession();
  393. $session->set('last-password-confirm', \OC::$server->query(ITimeFactory::class)->getTime());
  394. // Set email for admin
  395. if (!empty($options['adminemail'])) {
  396. $config->setUserValue($user->getUID(), 'settings', 'email', $options['adminemail']);
  397. }
  398. }
  399. return $error;
  400. }
  401. public static function installBackgroundJobs() {
  402. $jobList = \OC::$server->getJobList();
  403. $jobList->add(DefaultTokenCleanupJob::class);
  404. $jobList->add(Rotate::class);
  405. $jobList->add(BackgroundCleanupJob::class);
  406. }
  407. /**
  408. * @return string Absolute path to htaccess
  409. */
  410. private function pathToHtaccess() {
  411. return \OC::$SERVERROOT . '/.htaccess';
  412. }
  413. /**
  414. * Find webroot from config
  415. *
  416. * @param SystemConfig $config
  417. * @return string
  418. * @throws InvalidArgumentException when invalid value for overwrite.cli.url
  419. */
  420. private static function findWebRoot(SystemConfig $config): string {
  421. // For CLI read the value from overwrite.cli.url
  422. if (\OC::$CLI) {
  423. $webRoot = $config->getValue('overwrite.cli.url', '');
  424. if ($webRoot === '') {
  425. throw new InvalidArgumentException('overwrite.cli.url is empty');
  426. }
  427. if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
  428. throw new InvalidArgumentException('invalid value for overwrite.cli.url');
  429. }
  430. $webRoot = rtrim(parse_url($webRoot, PHP_URL_PATH), '/');
  431. } else {
  432. $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
  433. }
  434. return $webRoot;
  435. }
  436. /**
  437. * Append the correct ErrorDocument path for Apache hosts
  438. *
  439. * @return bool True when success, False otherwise
  440. * @throws \OCP\AppFramework\QueryException
  441. */
  442. public static function updateHtaccess() {
  443. $config = \OC::$server->getSystemConfig();
  444. try {
  445. $webRoot = self::findWebRoot($config);
  446. } catch (InvalidArgumentException $e) {
  447. return false;
  448. }
  449. $setupHelper = new \OC\Setup(
  450. $config,
  451. \OC::$server->get(IniGetWrapper::class),
  452. \OC::$server->getL10N('lib'),
  453. \OC::$server->query(Defaults::class),
  454. \OC::$server->getLogger(),
  455. \OC::$server->getSecureRandom(),
  456. \OC::$server->query(Installer::class)
  457. );
  458. $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
  459. $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
  460. $htaccessContent = explode($content, $htaccessContent, 2)[0];
  461. //custom 403 error page
  462. $content .= "\nErrorDocument 403 " . $webRoot . '/';
  463. //custom 404 error page
  464. $content .= "\nErrorDocument 404 " . $webRoot . '/';
  465. // Add rewrite rules if the RewriteBase is configured
  466. $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
  467. if ($rewriteBase !== '') {
  468. $content .= "\n<IfModule mod_rewrite.c>";
  469. $content .= "\n Options -MultiViews";
  470. $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
  471. $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
  472. $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav)$";
  473. $content .= "\n RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
  474. $content .= "\n RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
  475. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/remote.php";
  476. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/public.php";
  477. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/cron.php";
  478. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
  479. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/status.php";
  480. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
  481. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
  482. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots.txt";
  483. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/updater/";
  484. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
  485. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocm-provider/";
  486. $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
  487. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$";
  488. $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]";
  489. $content .= "\n RewriteBase " . $rewriteBase;
  490. $content .= "\n <IfModule mod_env.c>";
  491. $content .= "\n SetEnv front_controller_active true";
  492. $content .= "\n <IfModule mod_dir.c>";
  493. $content .= "\n DirectorySlash off";
  494. $content .= "\n </IfModule>";
  495. $content .= "\n </IfModule>";
  496. $content .= "\n</IfModule>";
  497. }
  498. if ($content !== '') {
  499. //suppress errors in case we don't have permissions for it
  500. return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
  501. }
  502. return false;
  503. }
  504. public static function protectDataDirectory() {
  505. //Require all denied
  506. $now = date('Y-m-d H:i:s');
  507. $content = "# Generated by Nextcloud on $now\n";
  508. $content .= "# Section for Apache 2.4 to 2.6\n";
  509. $content .= "<IfModule mod_authz_core.c>\n";
  510. $content .= " Require all denied\n";
  511. $content .= "</IfModule>\n";
  512. $content .= "<IfModule mod_access_compat.c>\n";
  513. $content .= " Order Allow,Deny\n";
  514. $content .= " Deny from all\n";
  515. $content .= " Satisfy All\n";
  516. $content .= "</IfModule>\n\n";
  517. $content .= "# Section for Apache 2.2\n";
  518. $content .= "<IfModule !mod_authz_core.c>\n";
  519. $content .= " <IfModule !mod_access_compat.c>\n";
  520. $content .= " <IfModule mod_authz_host.c>\n";
  521. $content .= " Order Allow,Deny\n";
  522. $content .= " Deny from all\n";
  523. $content .= " </IfModule>\n";
  524. $content .= " Satisfy All\n";
  525. $content .= " </IfModule>\n";
  526. $content .= "</IfModule>\n\n";
  527. $content .= "# Section for Apache 2.2 to 2.6\n";
  528. $content .= "<IfModule mod_autoindex.c>\n";
  529. $content .= " IndexIgnore *\n";
  530. $content .= "</IfModule>";
  531. $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
  532. file_put_contents($baseDir . '/.htaccess', $content);
  533. file_put_contents($baseDir . '/index.html', '');
  534. }
  535. /**
  536. * Return vendor from which this version was published
  537. *
  538. * @return string Get the vendor
  539. *
  540. * Copy of \OC\Updater::getVendor()
  541. */
  542. private function getVendor() {
  543. // this should really be a JSON file
  544. require \OC::$SERVERROOT . '/version.php';
  545. /** @var string $vendor */
  546. return (string)$vendor;
  547. }
  548. }