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.

Installer.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. if ($verified === true) {
  251. // Seems to match, let's proceed
  252. $extractDir = $this->tempManager->getTemporaryFolder();
  253. $archive = new TAR($tempFile);
  254. if (!$archive->extract($extractDir)) {
  255. $errorMessage = 'Could not extract app ' . $appId;
  256. $archiveError = $archive->getError();
  257. if ($archiveError instanceof \PEAR_Error) {
  258. $errorMessage .= ': ' . $archiveError->getMessage();
  259. }
  260. throw new \Exception($errorMessage);
  261. }
  262. $allFiles = scandir($extractDir);
  263. $folders = array_diff($allFiles, ['.', '..']);
  264. $folders = array_values($folders);
  265. if (count($folders) < 1) {
  266. throw new \Exception(
  267. sprintf(
  268. 'Extracted app %s has no folders',
  269. $appId
  270. )
  271. );
  272. }
  273. if (count($folders) > 1) {
  274. throw new \Exception(
  275. sprintf(
  276. 'Extracted app %s has more than 1 folder',
  277. $appId
  278. )
  279. );
  280. }
  281. // Check if appinfo/info.xml has the same app ID as well
  282. $xml = simplexml_load_string(file_get_contents($extractDir . '/' . $folders[0] . '/appinfo/info.xml'));
  283. if ($xml === false) {
  284. throw new \Exception(
  285. sprintf(
  286. 'Failed to load info.xml for app id %s',
  287. $appId,
  288. )
  289. );
  290. }
  291. if ((string)$xml->id !== $appId) {
  292. throw new \Exception(
  293. sprintf(
  294. 'App for id %s has a wrong app ID in info.xml: %s',
  295. $appId,
  296. (string)$xml->id
  297. )
  298. );
  299. }
  300. // Check if the version is lower than before
  301. $currentVersion = \OCP\Server::get(IAppManager::class)->getAppVersion($appId, true);
  302. $newVersion = (string)$xml->version;
  303. if (version_compare($currentVersion, $newVersion) === 1) {
  304. throw new \Exception(
  305. sprintf(
  306. 'App for id %s has version %s and tried to update to lower version %s',
  307. $appId,
  308. $currentVersion,
  309. $newVersion
  310. )
  311. );
  312. }
  313. $baseDir = OC_App::getInstallPath() . '/' . $appId;
  314. // Remove old app with the ID if existent
  315. OC_Helper::rmdirr($baseDir);
  316. // Move to app folder
  317. if (@mkdir($baseDir)) {
  318. $extractDir .= '/' . $folders[0];
  319. OC_Helper::copyr($extractDir, $baseDir);
  320. }
  321. OC_Helper::copyr($extractDir, $baseDir);
  322. OC_Helper::rmdirr($extractDir);
  323. return;
  324. }
  325. // Signature does not match
  326. throw new \Exception(
  327. sprintf(
  328. 'App with id %s has invalid signature',
  329. $appId
  330. )
  331. );
  332. }
  333. }
  334. throw new \Exception(
  335. sprintf(
  336. 'Could not download app %s',
  337. $appId
  338. )
  339. );
  340. }
  341. /**
  342. * Check if an update for the app is available
  343. *
  344. * @param string $appId
  345. * @param bool $allowUnstable
  346. * @return string|false false or the version number of the update
  347. */
  348. public function isUpdateAvailable($appId, $allowUnstable = false): string|false {
  349. if ($this->isInstanceReadyForUpdates === null) {
  350. $installPath = OC_App::getInstallPath();
  351. if ($installPath === null) {
  352. $this->isInstanceReadyForUpdates = false;
  353. } else {
  354. $this->isInstanceReadyForUpdates = true;
  355. }
  356. }
  357. if ($this->isInstanceReadyForUpdates === false) {
  358. return false;
  359. }
  360. if ($this->isInstalledFromGit($appId) === true) {
  361. return false;
  362. }
  363. if ($this->apps === null) {
  364. $this->apps = $this->appFetcher->get($allowUnstable);
  365. }
  366. foreach ($this->apps as $app) {
  367. if ($app['id'] === $appId) {
  368. $currentVersion = \OCP\Server::get(IAppManager::class)->getAppVersion($appId, true);
  369. if (!isset($app['releases'][0]['version'])) {
  370. return false;
  371. }
  372. $newestVersion = $app['releases'][0]['version'];
  373. if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
  374. return $newestVersion;
  375. } else {
  376. return false;
  377. }
  378. }
  379. }
  380. return false;
  381. }
  382. /**
  383. * Check if app has been installed from git
  384. *
  385. * The function will check if the path contains a .git folder
  386. */
  387. private function isInstalledFromGit(string $appId): bool {
  388. $app = \OC_App::findAppInDirectories($appId);
  389. if ($app === false) {
  390. return false;
  391. }
  392. $basedir = $app['path'].'/'.$appId;
  393. return file_exists($basedir.'/.git/');
  394. }
  395. /**
  396. * Check if app is already downloaded
  397. *
  398. * The function will check if the app is already downloaded in the apps repository
  399. */
  400. public function isDownloaded(string $name): bool {
  401. foreach (\OC::$APPSROOTS as $dir) {
  402. $dirToTest = $dir['path'];
  403. $dirToTest .= '/';
  404. $dirToTest .= $name;
  405. $dirToTest .= '/';
  406. if (is_dir($dirToTest)) {
  407. return true;
  408. }
  409. }
  410. return false;
  411. }
  412. /**
  413. * Removes an app
  414. *
  415. * This function works as follows
  416. * -# call uninstall repair steps
  417. * -# removing the files
  418. *
  419. * The function will not delete preferences, tables and the configuration,
  420. * this has to be done by the function oc_app_uninstall().
  421. */
  422. public function removeApp(string $appId): bool {
  423. if ($this->isDownloaded($appId)) {
  424. if (\OCP\Server::get(IAppManager::class)->isShipped($appId)) {
  425. return false;
  426. }
  427. $appDir = OC_App::getInstallPath() . '/' . $appId;
  428. OC_Helper::rmdirr($appDir);
  429. return true;
  430. } else {
  431. $this->logger->error('can\'t remove app '.$appId.'. It is not installed.');
  432. return false;
  433. }
  434. }
  435. /**
  436. * Installs the app within the bundle and marks the bundle as installed
  437. *
  438. * @throws \Exception If app could not get installed
  439. */
  440. public function installAppBundle(Bundle $bundle): void {
  441. $appIds = $bundle->getAppIdentifiers();
  442. foreach ($appIds as $appId) {
  443. if (!$this->isDownloaded($appId)) {
  444. $this->downloadApp($appId);
  445. }
  446. $this->installApp($appId);
  447. $app = new OC_App();
  448. $app->enable($appId);
  449. }
  450. $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
  451. $bundles[] = $bundle->getIdentifier();
  452. $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
  453. }
  454. /**
  455. * Installs shipped apps
  456. *
  457. * This function installs all apps found in the 'apps' directory that should be enabled by default;
  458. * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
  459. * working ownCloud at the end instead of an aborted update.
  460. * @return array Array of error messages (appid => Exception)
  461. */
  462. public static function installShippedApps(bool $softErrors = false, ?IOutput $output = null): array {
  463. if ($output instanceof IOutput) {
  464. $output->debug('Installing shipped apps');
  465. }
  466. $appManager = \OCP\Server::get(IAppManager::class);
  467. $config = \OCP\Server::get(IConfig::class);
  468. $errors = [];
  469. foreach (\OC::$APPSROOTS as $app_dir) {
  470. if ($dir = opendir($app_dir['path'])) {
  471. while (false !== ($filename = readdir($dir))) {
  472. if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
  473. if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
  474. if ($config->getAppValue($filename, "installed_version", null) === null) {
  475. $enabled = $appManager->isDefaultEnabled($filename);
  476. if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
  477. && $config->getAppValue($filename, 'enabled') !== 'no') {
  478. if ($softErrors) {
  479. try {
  480. Installer::installShippedApp($filename, $output);
  481. } catch (HintException $e) {
  482. if ($e->getPrevious() instanceof TableExistsException) {
  483. $errors[$filename] = $e;
  484. continue;
  485. }
  486. throw $e;
  487. }
  488. } else {
  489. Installer::installShippedApp($filename, $output);
  490. }
  491. $config->setAppValue($filename, 'enabled', 'yes');
  492. }
  493. }
  494. }
  495. }
  496. }
  497. closedir($dir);
  498. }
  499. }
  500. return $errors;
  501. }
  502. /**
  503. * install an app already placed in the app folder
  504. */
  505. public static function installShippedApp(string $app, ?IOutput $output = null): string|false {
  506. if ($output instanceof IOutput) {
  507. $output->debug('Installing ' . $app);
  508. }
  509. $appManager = \OCP\Server::get(IAppManager::class);
  510. $config = \OCP\Server::get(IConfig::class);
  511. $appPath = $appManager->getAppPath($app);
  512. \OC_App::registerAutoloading($app, $appPath);
  513. $ms = new MigrationService($app, \OCP\Server::get(Connection::class));
  514. if ($output instanceof IOutput) {
  515. $ms->setOutput($output);
  516. }
  517. $previousVersion = $config->getAppValue($app, 'installed_version', false);
  518. $ms->migrate('latest', !$previousVersion);
  519. //run appinfo/install.php
  520. self::includeAppScript("$appPath/appinfo/install.php");
  521. $info = \OCP\Server::get(IAppManager::class)->getAppInfo($app);
  522. if (is_null($info)) {
  523. return false;
  524. }
  525. if ($output instanceof IOutput) {
  526. $output->debug('Registering tasks of ' . $app);
  527. }
  528. \OC_App::setupBackgroundJobs($info['background-jobs']);
  529. OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
  530. $config->setAppValue($app, 'installed_version', \OCP\Server::get(IAppManager::class)->getAppVersion($app));
  531. if (array_key_exists('ocsid', $info)) {
  532. $config->setAppValue($app, 'ocsid', $info['ocsid']);
  533. }
  534. //set remote/public handlers
  535. foreach ($info['remote'] as $name => $path) {
  536. $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
  537. }
  538. foreach ($info['public'] as $name => $path) {
  539. $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
  540. }
  541. OC_App::setAppTypes($info['id']);
  542. return $info['id'];
  543. }
  544. private static function includeAppScript(string $script): void {
  545. if (file_exists($script)) {
  546. include $script;
  547. }
  548. }
  549. }