Installer.php 19 KB

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