Installer.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch>
  6. *
  7. * @author acsfer <carlos@reendex.com>
  8. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  9. * @author Brice Maron <brice@bmaron.net>
  10. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  11. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  12. * @author Frank Karlitschek <frank@karlitschek.de>
  13. * @author Georg Ehrke <oc.list@georgehrke.com>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author John Molakvoæ <skjnldsv@protonmail.com>
  16. * @author Julius Härtl <jus@bitgrid.net>
  17. * @author Kamil Domanski <kdomanski@kdemail.net>
  18. * @author Lukas Reschke <lukas@statuscode.ch>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author root "root@oc.(none)"
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Thomas Tanghus <thomas@tanghus.net>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. namespace OC;
  42. use Doctrine\DBAL\Exception\TableExistsException;
  43. use OC\App\AppStore\Bundles\Bundle;
  44. use OC\App\AppStore\Fetcher\AppFetcher;
  45. use OC\AppFramework\Bootstrap\Coordinator;
  46. use OC\Archive\TAR;
  47. use OC\DB\Connection;
  48. use OC\DB\MigrationService;
  49. use OC_App;
  50. use OC_Helper;
  51. use OCP\App\IAppManager;
  52. use OCP\HintException;
  53. use OCP\Http\Client\IClientService;
  54. use OCP\IConfig;
  55. use OCP\ITempManager;
  56. use OCP\Migration\IOutput;
  57. use phpseclib\File\X509;
  58. use Psr\Log\LoggerInterface;
  59. /**
  60. * This class provides the functionality needed to install, update and remove apps
  61. */
  62. class Installer {
  63. private ?bool $isInstanceReadyForUpdates = null;
  64. private ?array $apps = null;
  65. public function __construct(
  66. private AppFetcher $appFetcher,
  67. private IClientService $clientService,
  68. private ITempManager $tempManager,
  69. private LoggerInterface $logger,
  70. private IConfig $config,
  71. private bool $isCLI,
  72. ) {
  73. }
  74. /**
  75. * Installs an app that is located in one of the app folders already
  76. *
  77. * @param string $appId App to install
  78. * @param bool $forceEnable
  79. * @throws \Exception
  80. * @return string app ID
  81. */
  82. public function installApp(string $appId, bool $forceEnable = false): string {
  83. $app = \OC_App::findAppInDirectories($appId);
  84. if ($app === false) {
  85. throw new \Exception('App not found in any app directory');
  86. }
  87. $basedir = $app['path'].'/'.$appId;
  88. if (is_file($basedir . '/appinfo/database.xml')) {
  89. throw new \Exception('The appinfo/database.xml file is not longer supported. Used in ' . $appId);
  90. }
  91. $l = \OCP\Util::getL10N('core');
  92. $info = \OCP\Server::get(IAppManager::class)->getAppInfo($basedir . '/appinfo/info.xml', true, $l->getLanguageCode());
  93. if (!is_array($info)) {
  94. throw new \Exception(
  95. $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
  96. [$appId]
  97. )
  98. );
  99. }
  100. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  101. $ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true);
  102. $version = implode('.', \OCP\Util::getVersion());
  103. if (!\OC_App::isAppCompatible($version, $info, $ignoreMax)) {
  104. throw new \Exception(
  105. // TODO $l
  106. $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
  107. [$info['name']]
  108. )
  109. );
  110. }
  111. // check for required dependencies
  112. \OC_App::checkAppDependencies($this->config, $l, $info, $ignoreMax);
  113. /** @var Coordinator $coordinator */
  114. $coordinator = \OC::$server->get(Coordinator::class);
  115. $coordinator->runLazyRegistration($appId);
  116. \OC_App::registerAutoloading($appId, $basedir);
  117. $previousVersion = $this->config->getAppValue($info['id'], 'installed_version', false);
  118. if ($previousVersion) {
  119. OC_App::executeRepairSteps($appId, $info['repair-steps']['pre-migration']);
  120. }
  121. //install the database
  122. $ms = new MigrationService($info['id'], \OCP\Server::get(Connection::class));
  123. $ms->migrate('latest', !$previousVersion);
  124. if ($previousVersion) {
  125. OC_App::executeRepairSteps($appId, $info['repair-steps']['post-migration']);
  126. }
  127. \OC_App::setupBackgroundJobs($info['background-jobs']);
  128. //run appinfo/install.php
  129. self::includeAppScript($basedir . '/appinfo/install.php');
  130. OC_App::executeRepairSteps($appId, $info['repair-steps']['install']);
  131. $config = \OCP\Server::get(IConfig::class);
  132. //set the installed version
  133. $config->setAppValue($info['id'], 'installed_version', \OCP\Server::get(IAppManager::class)->getAppVersion($info['id'], false));
  134. $config->setAppValue($info['id'], 'enabled', 'no');
  135. //set remote/public handlers
  136. foreach ($info['remote'] as $name => $path) {
  137. $config->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
  138. }
  139. foreach ($info['public'] as $name => $path) {
  140. $config->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
  141. }
  142. OC_App::setAppTypes($info['id']);
  143. return $info['id'];
  144. }
  145. /**
  146. * Updates the specified app from the appstore
  147. *
  148. * @param bool $allowUnstable Allow unstable releases
  149. */
  150. public function updateAppstoreApp(string $appId, bool $allowUnstable = false): bool {
  151. if ($this->isUpdateAvailable($appId, $allowUnstable)) {
  152. try {
  153. $this->downloadApp($appId, $allowUnstable);
  154. } catch (\Exception $e) {
  155. $this->logger->error($e->getMessage(), [
  156. 'exception' => $e,
  157. ]);
  158. return false;
  159. }
  160. return OC_App::updateApp($appId);
  161. }
  162. return false;
  163. }
  164. /**
  165. * Split the certificate file in individual certs
  166. *
  167. * @param string $cert
  168. * @return string[]
  169. */
  170. private function splitCerts(string $cert): array {
  171. preg_match_all('([\-]{3,}[\S\ ]+?[\-]{3,}[\S\s]+?[\-]{3,}[\S\ ]+?[\-]{3,})', $cert, $matches);
  172. return $matches[0];
  173. }
  174. /**
  175. * Downloads an app and puts it into the app directory
  176. *
  177. * @param string $appId
  178. * @param bool [$allowUnstable]
  179. *
  180. * @throws \Exception If the installation was not successful
  181. */
  182. public function downloadApp(string $appId, bool $allowUnstable = false): void {
  183. $appId = strtolower($appId);
  184. $apps = $this->appFetcher->get($allowUnstable);
  185. foreach ($apps as $app) {
  186. if ($app['id'] === $appId) {
  187. // Load the certificate
  188. $certificate = new X509();
  189. $rootCrt = file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt');
  190. $rootCrts = $this->splitCerts($rootCrt);
  191. foreach ($rootCrts as $rootCrt) {
  192. $certificate->loadCA($rootCrt);
  193. }
  194. $loadedCertificate = $certificate->loadX509($app['certificate']);
  195. // Verify if the certificate has been revoked
  196. $crl = new X509();
  197. foreach ($rootCrts as $rootCrt) {
  198. $crl->loadCA($rootCrt);
  199. }
  200. $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
  201. if ($crl->validateSignature() !== true) {
  202. throw new \Exception('Could not validate CRL signature');
  203. }
  204. $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
  205. $revoked = $crl->getRevoked($csn);
  206. if ($revoked !== false) {
  207. throw new \Exception(
  208. sprintf(
  209. 'Certificate "%s" has been revoked',
  210. $csn
  211. )
  212. );
  213. }
  214. // Verify if the certificate has been issued by the Nextcloud Code Authority CA
  215. if ($certificate->validateSignature() !== true) {
  216. throw new \Exception(
  217. sprintf(
  218. 'App with id %s has a certificate not issued by a trusted Code Signing Authority',
  219. $appId
  220. )
  221. );
  222. }
  223. // Verify if the certificate is issued for the requested app id
  224. $certInfo = openssl_x509_parse($app['certificate']);
  225. if (!isset($certInfo['subject']['CN'])) {
  226. throw new \Exception(
  227. sprintf(
  228. 'App with id %s has a cert with no CN',
  229. $appId
  230. )
  231. );
  232. }
  233. if ($certInfo['subject']['CN'] !== $appId) {
  234. throw new \Exception(
  235. sprintf(
  236. 'App with id %s has a cert issued to %s',
  237. $appId,
  238. $certInfo['subject']['CN']
  239. )
  240. );
  241. }
  242. // Download the release
  243. $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
  244. $timeout = $this->isCLI ? 0 : 120;
  245. $client = $this->clientService->newClient();
  246. $client->get($app['releases'][0]['download'], ['sink' => $tempFile, 'timeout' => $timeout]);
  247. // Check if the signature actually matches the downloaded content
  248. $certificate = openssl_get_publickey($app['certificate']);
  249. $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
  250. // PHP 8+ deprecates openssl_free_key and automatically destroys the key instance when it goes out of scope
  251. if ((PHP_VERSION_ID < 80000)) {
  252. openssl_free_key($certificate);
  253. }
  254. if ($verified === true) {
  255. // Seems to match, let's proceed
  256. $extractDir = $this->tempManager->getTemporaryFolder();
  257. $archive = new TAR($tempFile);
  258. if (!$archive->extract($extractDir)) {
  259. $errorMessage = 'Could not extract app ' . $appId;
  260. $archiveError = $archive->getError();
  261. if ($archiveError instanceof \PEAR_Error) {
  262. $errorMessage .= ': ' . $archiveError->getMessage();
  263. }
  264. throw new \Exception($errorMessage);
  265. }
  266. $allFiles = scandir($extractDir);
  267. $folders = array_diff($allFiles, ['.', '..']);
  268. $folders = array_values($folders);
  269. if (count($folders) > 1) {
  270. throw new \Exception(
  271. sprintf(
  272. 'Extracted app %s has more than 1 folder',
  273. $appId
  274. )
  275. );
  276. }
  277. // Check if appinfo/info.xml has the same app ID as well
  278. if ((PHP_VERSION_ID < 80000)) {
  279. $loadEntities = libxml_disable_entity_loader(false);
  280. $xml = simplexml_load_string(file_get_contents($extractDir . '/' . $folders[0] . '/appinfo/info.xml'));
  281. libxml_disable_entity_loader($loadEntities);
  282. } else {
  283. $xml = simplexml_load_string(file_get_contents($extractDir . '/' . $folders[0] . '/appinfo/info.xml'));
  284. }
  285. if ((string)$xml->id !== $appId) {
  286. throw new \Exception(
  287. sprintf(
  288. 'App for id %s has a wrong app ID in info.xml: %s',
  289. $appId,
  290. (string)$xml->id
  291. )
  292. );
  293. }
  294. // Check if the version is lower than before
  295. $currentVersion = \OCP\Server::get(IAppManager::class)->getAppVersion($appId, true);
  296. $newVersion = (string)$xml->version;
  297. if (version_compare($currentVersion, $newVersion) === 1) {
  298. throw new \Exception(
  299. sprintf(
  300. 'App for id %s has version %s and tried to update to lower version %s',
  301. $appId,
  302. $currentVersion,
  303. $newVersion
  304. )
  305. );
  306. }
  307. $baseDir = OC_App::getInstallPath() . '/' . $appId;
  308. // Remove old app with the ID if existent
  309. OC_Helper::rmdirr($baseDir);
  310. // Move to app folder
  311. if (@mkdir($baseDir)) {
  312. $extractDir .= '/' . $folders[0];
  313. OC_Helper::copyr($extractDir, $baseDir);
  314. }
  315. OC_Helper::copyr($extractDir, $baseDir);
  316. OC_Helper::rmdirr($extractDir);
  317. return;
  318. }
  319. // Signature does not match
  320. throw new \Exception(
  321. sprintf(
  322. 'App with id %s has invalid signature',
  323. $appId
  324. )
  325. );
  326. }
  327. }
  328. throw new \Exception(
  329. sprintf(
  330. 'Could not download app %s',
  331. $appId
  332. )
  333. );
  334. }
  335. /**
  336. * Check if an update for the app is available
  337. *
  338. * @param string $appId
  339. * @param bool $allowUnstable
  340. * @return string|false false or the version number of the update
  341. */
  342. public function isUpdateAvailable($appId, $allowUnstable = false): string|false {
  343. if ($this->isInstanceReadyForUpdates === null) {
  344. $installPath = OC_App::getInstallPath();
  345. if ($installPath === null) {
  346. $this->isInstanceReadyForUpdates = false;
  347. } else {
  348. $this->isInstanceReadyForUpdates = true;
  349. }
  350. }
  351. if ($this->isInstanceReadyForUpdates === false) {
  352. return false;
  353. }
  354. if ($this->isInstalledFromGit($appId) === true) {
  355. return false;
  356. }
  357. if ($this->apps === null) {
  358. $this->apps = $this->appFetcher->get($allowUnstable);
  359. }
  360. foreach ($this->apps as $app) {
  361. if ($app['id'] === $appId) {
  362. $currentVersion = \OCP\Server::get(IAppManager::class)->getAppVersion($appId, true);
  363. if (!isset($app['releases'][0]['version'])) {
  364. return false;
  365. }
  366. $newestVersion = $app['releases'][0]['version'];
  367. if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
  368. return $newestVersion;
  369. } else {
  370. return false;
  371. }
  372. }
  373. }
  374. return false;
  375. }
  376. /**
  377. * Check if app has been installed from git
  378. *
  379. * The function will check if the path contains a .git folder
  380. */
  381. private function isInstalledFromGit(string $appId): bool {
  382. $app = \OC_App::findAppInDirectories($appId);
  383. if ($app === false) {
  384. return false;
  385. }
  386. $basedir = $app['path'].'/'.$appId;
  387. return file_exists($basedir.'/.git/');
  388. }
  389. /**
  390. * Check if app is already downloaded
  391. *
  392. * The function will check if the app is already downloaded in the apps repository
  393. */
  394. public function isDownloaded(string $name): bool {
  395. foreach (\OC::$APPSROOTS as $dir) {
  396. $dirToTest = $dir['path'];
  397. $dirToTest .= '/';
  398. $dirToTest .= $name;
  399. $dirToTest .= '/';
  400. if (is_dir($dirToTest)) {
  401. return true;
  402. }
  403. }
  404. return false;
  405. }
  406. /**
  407. * Removes an app
  408. *
  409. * This function works as follows
  410. * -# call uninstall repair steps
  411. * -# removing the files
  412. *
  413. * The function will not delete preferences, tables and the configuration,
  414. * this has to be done by the function oc_app_uninstall().
  415. */
  416. public function removeApp(string $appId): bool {
  417. if ($this->isDownloaded($appId)) {
  418. if (\OCP\Server::get(IAppManager::class)->isShipped($appId)) {
  419. return false;
  420. }
  421. $appDir = OC_App::getInstallPath() . '/' . $appId;
  422. OC_Helper::rmdirr($appDir);
  423. return true;
  424. } else {
  425. $this->logger->error('can\'t remove app '.$appId.'. It is not installed.');
  426. return false;
  427. }
  428. }
  429. /**
  430. * Installs the app within the bundle and marks the bundle as installed
  431. *
  432. * @throws \Exception If app could not get installed
  433. */
  434. public function installAppBundle(Bundle $bundle): void {
  435. $appIds = $bundle->getAppIdentifiers();
  436. foreach ($appIds as $appId) {
  437. if (!$this->isDownloaded($appId)) {
  438. $this->downloadApp($appId);
  439. }
  440. $this->installApp($appId);
  441. $app = new OC_App();
  442. $app->enable($appId);
  443. }
  444. $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
  445. $bundles[] = $bundle->getIdentifier();
  446. $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
  447. }
  448. /**
  449. * Installs shipped apps
  450. *
  451. * This function installs all apps found in the 'apps' directory that should be enabled by default;
  452. * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
  453. * working ownCloud at the end instead of an aborted update.
  454. * @return array Array of error messages (appid => Exception)
  455. */
  456. public static function installShippedApps(bool $softErrors = false, ?IOutput $output = null): array {
  457. if ($output instanceof IOutput) {
  458. $output->debug('Installing shipped apps');
  459. }
  460. $appManager = \OCP\Server::get(IAppManager::class);
  461. $config = \OCP\Server::get(IConfig::class);
  462. $errors = [];
  463. foreach (\OC::$APPSROOTS as $app_dir) {
  464. if ($dir = opendir($app_dir['path'])) {
  465. while (false !== ($filename = readdir($dir))) {
  466. if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
  467. if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
  468. if ($config->getAppValue($filename, "installed_version", null) === null) {
  469. $enabled = $appManager->isDefaultEnabled($filename);
  470. if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
  471. && $config->getAppValue($filename, 'enabled') !== 'no') {
  472. if ($softErrors) {
  473. try {
  474. Installer::installShippedApp($filename, $output);
  475. } catch (HintException $e) {
  476. if ($e->getPrevious() instanceof TableExistsException) {
  477. $errors[$filename] = $e;
  478. continue;
  479. }
  480. throw $e;
  481. }
  482. } else {
  483. Installer::installShippedApp($filename, $output);
  484. }
  485. $config->setAppValue($filename, 'enabled', 'yes');
  486. }
  487. }
  488. }
  489. }
  490. }
  491. closedir($dir);
  492. }
  493. }
  494. return $errors;
  495. }
  496. /**
  497. * install an app already placed in the app folder
  498. */
  499. public static function installShippedApp(string $app, ?IOutput $output = null): string|false {
  500. if ($output instanceof IOutput) {
  501. $output->debug('Installing ' . $app);
  502. }
  503. $appManager = \OCP\Server::get(IAppManager::class);
  504. $config = \OCP\Server::get(IConfig::class);
  505. $appPath = $appManager->getAppPath($app);
  506. \OC_App::registerAutoloading($app, $appPath);
  507. $ms = new MigrationService($app, \OCP\Server::get(Connection::class));
  508. if ($output instanceof IOutput) {
  509. $ms->setOutput($output);
  510. }
  511. $previousVersion = $config->getAppValue($app, 'installed_version', false);
  512. $ms->migrate('latest', !$previousVersion);
  513. //run appinfo/install.php
  514. self::includeAppScript("$appPath/appinfo/install.php");
  515. $info = \OCP\Server::get(IAppManager::class)->getAppInfo($app);
  516. if (is_null($info)) {
  517. return false;
  518. }
  519. if ($output instanceof IOutput) {
  520. $output->debug('Registering tasks of ' . $app);
  521. }
  522. \OC_App::setupBackgroundJobs($info['background-jobs']);
  523. OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
  524. $config->setAppValue($app, 'installed_version', \OCP\Server::get(IAppManager::class)->getAppVersion($app));
  525. if (array_key_exists('ocsid', $info)) {
  526. $config->setAppValue($app, 'ocsid', $info['ocsid']);
  527. }
  528. //set remote/public handlers
  529. foreach ($info['remote'] as $name => $path) {
  530. $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
  531. }
  532. foreach ($info['public'] as $name => $path) {
  533. $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
  534. }
  535. OC_App::setAppTypes($info['id']);
  536. return $info['id'];
  537. }
  538. private static function includeAppScript(string $script): void {
  539. if (file_exists($script)) {
  540. include $script;
  541. }
  542. }
  543. }